TP 9 exo2: Fix linked list insert helper function.
[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_new;
7 link_new = malloc(sizeof(link_t));
8 link_new->value = value;
9 link_new->next = NULL;
10 return link_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
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;
52 }
53 }
54
55 link_t* list_delete(link_t* head, unsigned index) {
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 {
65 link_t* head_first = head;
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
79 unsigned list_count(link_t* head) {
80 int count = 0;
81
82 while (head != NULL) {
83 ++count;
84 head = head->next;
85 }
86 return count;
87 }
88
89 void list_set(link_t* head, unsigned index, int value) {
90 unsigned count = 0;
91
92 while (head != NULL && count < index) {
93 ++count;
94 head = head->next;
95 }
96 if (head != NULL) { head->value = value; }
97 }
98
99 int list_get(link_t* head, unsigned index) {
100 unsigned count = 0;
101
102 while (head != NULL && count < index) {
103 ++count;
104 head = head->next;
105 }
106 if (head != NULL) {
107 return head->value;
108 } else {
109 return -1;
110 }
111 }
112
113 void list_clear(link_t* link) {
114 link_t* next_link = NULL;
115
116 while (link != NULL) {
117 next_link = link->next;
118 free(link);
119 link = next_link;
120 }
121 }