aboutsummaryrefslogtreecommitdiff
path: root/lib/list.c
diff options
context:
space:
mode:
authorMarvin Borner2020-08-13 21:27:19 +0200
committerMarvin Borner2020-08-13 21:27:19 +0200
commitf540d4f3d3e6eeac98891da9326dfca6f472960a (patch)
tree9020e305f8b48d63f616c5f730663eb61a8a5574 /lib/list.c
parent54ece9141e9ad8cfb59f2c8315c84b8e247275f7 (diff)
Added basic list lib
Diffstat (limited to 'lib/list.c')
-rw-r--r--lib/list.c74
1 files changed, 74 insertions, 0 deletions
diff --git a/lib/list.c b/lib/list.c
new file mode 100644
index 0000000..c36d6e1
--- /dev/null
+++ b/lib/list.c
@@ -0,0 +1,74 @@
+// MIT License, Copyright (c) 2020 Marvin Borner
+
+#include <def.h>
+#include <list.h>
+#include <mem.h>
+
+static int nonce = 0;
+
+struct list *list_new()
+{
+ struct list *list = malloc(sizeof(*list));
+ list->head = NULL;
+ return list;
+}
+
+struct node *list_new_node()
+{
+ struct node *node = malloc(sizeof(*node));
+ node->data = NULL;
+ node->prev = NULL;
+ node->next = NULL;
+ node->nonce = nonce++;
+ return node;
+}
+
+void list_add_node(struct list *list, struct node *node)
+{
+ if (list == NULL)
+ return;
+
+ if (list->head == NULL) {
+ list->head = node;
+ return;
+ }
+
+ struct node *iterator = list->head;
+ while (iterator != NULL) {
+ if (iterator->next == NULL) {
+ iterator->next = node;
+ node->prev = iterator;
+ break;
+ }
+ iterator = iterator->next;
+ }
+}
+
+void list_add(struct list *list, void *data)
+{
+ struct node *node = list_new_node();
+ node->data = data;
+ list_add_node(list, node);
+}
+
+// Maybe list_remove_node?
+void list_remove(struct list *list, struct node *node)
+{
+ if (list == NULL || list->head == NULL)
+ return;
+
+ if (list->head == node) {
+ list->head = list->head->next;
+ return;
+ }
+
+ struct node *iterator = list->head->next;
+ while (iterator != node) {
+ iterator = iterator->next;
+ if (iterator == NULL)
+ return;
+ }
+
+ iterator->prev->next = iterator->next;
+ iterator->next->prev = iterator->prev;
+}