TP 9 exo2: Fix linked list insert helper function.
[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) {
8f2b2843
JB
6 link_t* link_new;
7 link_new = malloc(sizeof(link_t));
8 link_new->value = value;
9 link_new->next = NULL;
10 return link_new;
f8051b35
JB
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
0d650b41 34link_t* list_insert(link_t* head, unsigned index, int value) {
0d650b41 35
3de00528
JB
36 if (index == 0) {
37 return list_prepend(head, value);
38 } else if (index == list_count(head)) {
39 return list_append(head, value);
40 } else {
41 link_t* link_insrt = list_new(value);
42 link_t* head_first = head;
43 link_t* head_next = NULL;
44 for (unsigned i = 0; i < index-1; i++) {
45 head = head->next;
46 }
47 head_next = head->next;
48 head->next = link_insrt;
49 head = link_insrt;
50 head->next = head_next;
51 return head_first;
0d650b41 52 }
0d650b41
JB
53}
54
55link_t* list_delete(link_t* head, unsigned index) {
0d650b41
JB
56 link_t* head_prev = NULL;
57 link_t* head_next = NULL;
58
59 if (index == 0) {
60 head_next = head->next;
61 free(head);
62 head = head_next;
63 return head;
64 } else {
3de00528 65 link_t* head_first = head;
0d650b41
JB
66 for (unsigned i = 0; i < index-1; i++) {
67 head = head->next;
68 }
69 head_prev = head;
70 head = head->next;
71 head_next = head->next;
72 free(head);
73 head = head_prev;
74 head->next = head_next;
75 return head_first;
76 }
77}
78
f8051b35 79unsigned list_count(link_t* head) {
490c6927 80 int count = 0;
f8051b35 81
8f2b2843 82 while (head != NULL) {
f8051b35
JB
83 ++count;
84 head = head->next;
85 }
86 return count;
87}
88
89void list_set(link_t* head, unsigned index, int value) {
8f2b2843 90 unsigned count = 0;
f8051b35 91
8f2b2843
JB
92 while (head != NULL && count < index) {
93 ++count;
f8051b35
JB
94 head = head->next;
95 }
8f2b2843 96 if (head != NULL) { head->value = value; }
f8051b35
JB
97}
98
99int list_get(link_t* head, unsigned index) {
8f2b2843
JB
100 unsigned count = 0;
101
102 while (head != NULL && count < index) {
103 ++count;
104 head = head->next;
105 }
106 if (head != NULL) {
f8051b35 107 return head->value;
8f2b2843 108 } else {
f8051b35
JB
109 return -1;
110 }
111}
112
113void list_clear(link_t* link) {
8f2b2843 114 link_t* next_link = NULL;
f8051b35
JB
115
116 while (link != NULL) {
8f2b2843 117 next_link = link->next;
f8051b35
JB
118 free(link);
119 link = next_link;
120 }
121}