TP_9 exo2: preliminary work on linked list helpers.
[TD_C.git] / TP_9 / exo2 / clist.c
1 #include <stdlib.h>
2
3 #include "clist.h"
4
5 link_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
13 link_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
27 link_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
34 unsigned list_count(link_t* head) {
35 int count = 1;
36
37 if (head == NULL) { return 0; }
38 while (head->next != NULL) {
39 ++count;
40 head = head->next;
41 }
42 return count;
43 }
44
45 void list_set(link_t* head, unsigned index, int value) {
46
47 // FIXME: check for the index value validity
48 for (unsigned count = 0; count < index; count++) {
49 head = head->next;
50 }
51 head->value = value;
52 }
53
54 int list_get(link_t* head, unsigned index) {
55
56 if (index < list_count(head)) {
57 for (unsigned i = 0; i < index; i++) {
58 head = head->next;
59 }
60 return head->value;
61 } else {
62 return -1;
63 }
64 }
65
66 void list_clear(link_t* link) {
67
68 while (link != NULL) {
69 link_t* next_link = link->next;
70 free(link);
71 link = next_link;
72 }
73 }