TP_9 exo1: split the linked list implementation into reusable code
[TD_C.git] / TP_9 / exo1 / clist.c
diff --git a/TP_9/exo1/clist.c b/TP_9/exo1/clist.c
new file mode 100644 (file)
index 0000000..69fd8cc
--- /dev/null
@@ -0,0 +1,51 @@
+#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;
+}
+
+void list_append(link_t* head, int value) {
+       
+    while (head->next != NULL) {
+       head = head->next; 
+    }
+    head->next = list_new(value);
+}
+
+unsigned list_count(link_t* head) {
+    // And if head is not defined? 
+    int count = 1;
+
+    while (head->next != NULL) {
+        ++count;
+        head = head->next;
+    } 
+    return count;
+}
+
+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;
+        free(link);
+        link = next_link;
+    }
+}