2e0352de109dfede2612bc175e0a6e9ab85c4c63
[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 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 while (head != NULL) {
79 ++count;
80 head = head->next;
81 }
82 return count;
83 }
84
85 void list_set(link_t* head, unsigned index, int value) {
86 unsigned count = 0;
87
88 while (head != NULL && count < index) {
89 ++count;
90 head = head->next;
91 }
92 if (head != NULL) { head->value = value; }
93 }
94
95 int list_get(link_t* head, unsigned index) {
96 unsigned count = 0;
97
98 while (head != NULL && count < index) {
99 ++count;
100 head = head->next;
101 }
102 if (head != NULL) {
103 return head->value;
104 } else {
105 return -1;
106 }
107 }
108
109 void list_clear(link_t* link) {
110 link_t* next_link = NULL;
111
112 while (link != NULL) {
113 next_link = link->next;
114 free(link);
115 link = next_link;
116 }
117 }