#include #include #include "sllist.h" Sllist *new_sllist() { Sllist *l; l = (Sllist *) malloc(sizeof(Sllist)); l->head = NULL; l->tail = NULL; return l; } void free_sllist(Sllist *l) { Sllist_Node *current_node, *next_node; for (current_node = l->head; current_node != NULL; current_node = next_node) { next_node = current_node->next; free(current_node); } free(l); } Sllist_Node *sll_prepend(Sllist *l, void *val) { Sllist_Node *tmp; tmp = (Sllist_Node *) malloc(sizeof(Sllist_Node)); tmp->val = val; tmp->next = l->head; // make the new element be the head of the list l->head = tmp; // if the list was empty, make the tail point to the new element if (l->tail == NULL) l->tail = tmp; return tmp; } Sllist_Node *sll_append(Sllist *l, void *val) { Sllist_Node *tmp; tmp = (Sllist_Node *) malloc(sizeof(Sllist_Node)); tmp->val = val; tmp->next = NULL; // make the previous tail point to this new element and then update // the list's tail to point to the new element if (l->tail != NULL) l->tail->next = tmp; l->tail = tmp; // if the list was empty, made the head point to the new element if (l->head == NULL) l->head = tmp; return tmp; } Sllist_Node *sll_insert_after(Sllist *l, Sllist_Node *node, void *val) { Sllist_Node *tmp; tmp = (Sllist_Node *) malloc(sizeof(Sllist_Node)); tmp->val = val; tmp->next = node->next; node->next = tmp; /* if node was the previous tail of the list, then the new element becomes the new tail of the list */ if (l->tail == node) l->tail = tmp; return tmp; } Sllist_Node *sll_first(Sllist *l) { return l->head; } Sllist_Node *sll_last(Sllist *l) { return l->tail; } Sllist_Node *sll_next(Sllist_Node *n) { return n->next; } void *sll_val(Sllist_Node *n) { return n->val; } int sll_empty(Sllist *l) { return (l->head == NULL); }