TP 9 exo2: handle out of bound list operations properly.
[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
JB
34link_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
51link_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
f8051b35 75unsigned list_count(link_t* head) {
490c6927 76 int count = 0;
f8051b35 77
8f2b2843 78 while (head != NULL) {
f8051b35
JB
79 ++count;
80 head = head->next;
81 }
82 return count;
83}
84
85void list_set(link_t* head, unsigned index, int value) {
8f2b2843 86 unsigned count = 0;
f8051b35 87
8f2b2843
JB
88 while (head != NULL && count < index) {
89 ++count;
f8051b35
JB
90 head = head->next;
91 }
8f2b2843 92 if (head != NULL) { head->value = value; }
f8051b35
JB
93}
94
95int list_get(link_t* head, unsigned index) {
8f2b2843
JB
96 unsigned count = 0;
97
98 while (head != NULL && count < index) {
99 ++count;
100 head = head->next;
101 }
102 if (head != NULL) {
f8051b35 103 return head->value;
8f2b2843 104 } else {
f8051b35
JB
105 return -1;
106 }
107}
108
109void list_clear(link_t* link) {
8f2b2843 110 link_t* next_link = NULL;
f8051b35
JB
111
112 while (link != NULL) {
8f2b2843 113 next_link = link->next;
f8051b35
JB
114 free(link);
115 link = next_link;
116 }
117}