TP_9 exo2: update Makefile
[TD_C.git] / TP_9 / exo2 / clist.c
CommitLineData
f8051b35
JB
1#include <stdlib.h>
2
3#include "clist.h"
4
5link_t* list_new(int value) {
6 link_t* link_t_new;
7 link_t_new = malloc(sizeof(link_t));
8 link_t_new->value = value;
9 link_t_new->next = NULL;
10 return link_t_new;
11}
12
13link_t* list_append(link_t* head, int value) {
14
15 if (head == NULL) {
16 return head = list_new(value);
17 } else {
18 link_t* head_first = head;
19 while (head->next != NULL) {
20 head = head->next;
21 }
22 head->next = list_new(value);
23 return head_first;
24 }
25}
26
27link_t* list_prepend(link_t* head, int value) {
28 link_t* first_link = list_new(value);
29
30 first_link->next = head;
31 return first_link;
32}
33
34unsigned list_count(link_t* head) {
490c6927 35 int count = 0;
f8051b35 36
490c6927
JB
37 if (head == NULL) { return count; }
38 count = 1;
f8051b35
JB
39 while (head->next != NULL) {
40 ++count;
41 head = head->next;
42 }
43 return count;
44}
45
46void list_set(link_t* head, unsigned index, int value) {
47
220a3455 48 //FIXME: check for the index value validity
f8051b35
JB
49 for (unsigned count = 0; count < index; count++) {
50 head = head->next;
51 }
52 head->value = value;
53}
54
55int list_get(link_t* head, unsigned index) {
56
57 if (index < list_count(head)) {
58 for (unsigned i = 0; i < index; i++) {
59 head = head->next;
60 }
61 return head->value;
62 } else {
63 return -1;
64 }
65}
66
67void list_clear(link_t* link) {
68
69 while (link != NULL) {
70 link_t* next_link = link->next;
71 free(link);
72 link = next_link;
73 }
74}