TP 9 exo2: Add list_insert and list_delete 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 link_t* list_insert(link_t* head, unsigned index, int value) {
35 link_t* link_insrt = list_new(value);
36 link_t* head_first = head;
37 //link_t* head_prev = NULL;
38 link_t* head_next = NULL;
39
40 for (unsigned i = 0; i < index; i++) {
41 head = head->next;
42 }
43 //head_prev = head;
44 head->next = link_insrt;
45 head_next = head->next;
46 head = link_insrt;
47 head->next = head_next;
48 return head_first;
49 }
50
51 link_t* list_delete(link_t* head, unsigned index) {
52 link_t* head_first = head;
53 link_t* head_prev = NULL;
54 link_t* head_next = NULL;
55
56 if (index == 0) {
57 head_next = head->next;
58 free(head);
59 head = head_next;
60 return head;
61 } else {
62 for (unsigned i = 0; i < index-1; i++) {
63 head = head->next;
64 }
65 head_prev = head;
66 head = head->next;
67 head_next = head->next;
68 free(head);
69 head = head_prev;
70 head->next = head_next;
71 return head_first;
72 }
73 }
74
75 unsigned list_count(link_t* head) {
76 int count = 0;
77
78 if (head == NULL) { return count; }
79 count = 1;
80 while (head->next != NULL) {
81 ++count;
82 head = head->next;
83 }
84 return count;
85 }
86
87 void list_set(link_t* head, unsigned index, int value) {
88
89 //FIXME: check for the index value validity
90 for (unsigned count = 0; count < index; count++) {
91 head = head->next;
92 }
93 head->value = value;
94 }
95
96 int list_get(link_t* head, unsigned index) {
97
98 if (index < list_count(head)) {
99 for (unsigned i = 0; i < index; i++) {
100 head = head->next;
101 }
102 return head->value;
103 } else {
104 return -1;
105 }
106 }
107
108 void list_clear(link_t* link) {
109
110 while (link != NULL) {
111 link_t* next_link = link->next;
112 free(link);
113 link = next_link;
114 }
115 }