#include #include "single_list.h" void single_node_init( single_node_t *const node, int v, single_node_t *n ); void single_node_init( single_node_t *const node, int v, single_node_t *n ) { node->value = v; node->next = n; } // Set the head and tail to NULL and the size is 0. void single_list_init( single_list_t *const list ) { list->head = NULL; list->tail = NULL; list->size = 0; } void single_list_destroy( single_list_t *const list ) { // Remove all remaining nodes in the linked list // - note that this is not recursive while ( list->size != 0 ) { single_list_pop_front( list ); } } int single_list_front( single_list_t *const list ) { // If the list is empty, return 0 if ( list->size == 0 ) { return 0; } return list->head->value; } int single_list_back( single_list_t *const list ) { // If the list is empty, return 0 if ( list->size == 0 ) { return 0; } return list->tail->value; } void single_list_push_front( single_list_t *const list, int n ) { // Create a new node that stores 'n' and points to the node // currently stored in 'head'. Assign the address of // this new node to 'head'. single_node_t *new_head = (single_node_t *) malloc( sizeof( single_node_t ) ); single_node_init( new_head, n, list->head ); list->head = new_head; // If the list was empty prior to this function being called, // we need to have 'tail' point to the same node as 'head'. if ( list->size == 0 ) { list->tail = list->head; } // Increment the number of nodes stored in this linked list ++( list->size ); } void single_list_pop_front( single_list_t *const list ) { single_node_t *tmp; // If it is empty, do nothing if ( list->size == 0 ) { return; } // Temporarily store the address of the node currently at the head of // the linked list, set 'head' to be the address of the node // pointed to by the current head of the linked list, and then // free the temporary node. tmp = list->head; list->head = list->head->next; free( tmp ); // Decrement the number of nodes stored in this linked list --( list->size ); // If the list is now empty, set the tail pointer to null, as well if ( list->size == 0 ) { list->tail = NULL; } }