TP_9 exo2: preliminary work on linked list helpers.
[TD_C.git] / TP_9 / exo2 / clist.c
diff --git a/TP_9/exo2/clist.c b/TP_9/exo2/clist.c
new file mode 100644 (file)
index 0000000..db08117
--- /dev/null
@@ -0,0 +1,73 @@
+#include <stdlib.h>
+
+#include "clist.h"
+
+link_t* list_new(int value) {
+    link_t* link_t_new;        
+    link_t_new = malloc(sizeof(link_t));
+    link_t_new->value = value;
+    link_t_new->next = NULL;
+    return link_t_new;
+}
+
+link_t* list_append(link_t* head, int value) {
+
+    if (head == NULL) { 
+        return head = list_new(value);
+    } else {
+        link_t* head_first = head;
+        while (head->next != NULL) {
+           head = head->next; 
+        }
+        head->next = list_new(value);
+        return head_first;
+    }
+}
+
+link_t* list_prepend(link_t* head, int value) {
+    link_t* first_link = list_new(value);
+    
+    first_link->next = head;
+    return first_link;
+}
+
+unsigned list_count(link_t* head) {
+    int count = 1;
+    
+    if (head == NULL) { return 0; }
+    while (head->next != NULL) {
+        ++count;
+        head = head->next;
+    } 
+    return count;
+}
+
+void list_set(link_t* head, unsigned index, int value) {
+
+    // FIXME: check for the index value validity
+    for (unsigned count = 0; count < index; count++) {
+        head = head->next;
+    }
+    head->value = value;
+}
+
+int list_get(link_t* head, unsigned index) {
+    
+    if (index < list_count(head)) {
+        for (unsigned i = 0; i < index; i++) {
+            head = head->next; 
+        }
+        return head->value;
+    } else { 
+        return -1;
+    }
+}
+
+void list_clear(link_t* link) {
+
+    while (link != NULL) {
+        link_t* next_link = link->next;
+        free(link);
+        link = next_link;
+    }
+}