diff options
-rw-r--r-- | linked_list.c | 59 | ||||
-rw-r--r-- | linked_list.h | 18 |
2 files changed, 77 insertions, 0 deletions
diff --git a/linked_list.c b/linked_list.c new file mode 100644 index 0000000..792da4d --- /dev/null +++ b/linked_list.c @@ -0,0 +1,59 @@ +#include <stdlib.h> +#include "linked_list.h" + +linked_list *add_node(linked_list **tail, void *data) { + if (tail == NULL) { + return NULL; + } else { + linked_list *node = calloc(1, sizeof(linked_list)); + if (node == NULL) { + return NULL; + } else { + node->next = NULL; + node->data = data; + + if (*tail == NULL) { + node->prev = NULL; + *tail = node; + } else { + (*tail)->next = node; + node->prev = *tail; + } + + return node; + } + } +} + + +void remove_node(linked_list *node) { + if (node != NULL) { + if (node->prev != NULL) { + node->prev->next = node->next; + } + + if (node->next != NULL) { + node->next->prev = node->prev; + } + + free(node); + } +} + +linked_list *get_head(linked_list *node) { + linked_list *head; + for (head = node; head != NULL && head->prev != NULL; head = head->prev); + return head; +} + +linked_list *get_tail(linked_list *node) { + linked_list *tail; + for (tail = node; tail != NULL && tail->next != NULL; tail = tail->next); + return tail; +} + +int linked_list_size(linked_list *tail) { + int i = 0; + for (linked_list *node = tail; node != NULL; node = node->prev, ++i); + return i; +} diff --git a/linked_list.h b/linked_list.h new file mode 100644 index 0000000..643e4f2 --- /dev/null +++ b/linked_list.h @@ -0,0 +1,18 @@ +#ifndef LINKED_LIST_H +#define LINKED_LIST_H + +typedef struct linked_list linked_list; + +struct linked_list { + linked_list *next; /* Next node in the list. */ + linked_list *prev; /* Previous node in the list. */ + void *data; /* Pointer to data. */ +}; + +extern linked_list *add_node(linked_list **tail, void *data); +extern void remove_node(linked_list *node); +extern linked_list *get_head(linked_list *node); +extern linked_list *get_tail(linked_list *node); +extern int linked_list_size(linked_list *tail); + +#endif |