#include "linked_list.h" #include #include void init_linked_list( linked_list_t *p_list ) { p_list->p_head = NULL; p_list->p_tail = NULL; p_list->size = 0; } int front( linked_list_t *p_list, bool *p_valid ) { int p_front_value = NULL; if ( p_list->size == 0 ) { *p_valid = false; } else { *p_valid = true; p_front_value = p_list->p_head->value; } return p_front_value; } int back( linked_list_t *p_list, bool *p_valid ) { int p_back_value = NULL; if ( p_list->size == 0 ) { *p_valid = false; } else { *p_valid = true; p_back_value = p_list->p_tail->value; } return p_back_value; } void push_front( linked_list_t *p_list, int new_value ) { if ( p_list->size == 0 ) { // Allocate memory for a new node p_list->p_head = (node_t *)malloc( sizeof( node_t ) ); // Initialize the new node p_list->p_head->value = new_value; p_list->p_tail = p_list->p_head; p_list->size = 1; } else { // Allocate memory for a new node node_t *p_new_node = (node_t *)malloc( sizeof( node_t ) ); // Initialize the new node p_new_node->value = new_value; p_new_node->p_next = p_list->p_head; p_list->p_head = p_new_node; ++( p_list->size ); } } void push_back( linked_list_t *p_list, int new_value ) { if ( p_list->size == 0 ) { // Let's not repeat ourselves... push_front( p_list, new_value ); } else { // Allocate memory for a new node p_list->p_tail->p_next = (node_t *)malloc( sizeof( node_t ) ); p_list->p_tail = p_list->p_tail->p_next; // Initialize the new node p_list->p_tail->value = new_value; p_list->p_tail->p_next = NULL; ++( p_list->size ); } } void pop_front( linked_list_t *p_list ) { if ( p_list->size == 1 ) { // Deallocate memory for the one node free( p_list->p_head ); // Reset the linked list p_list->p_head = NULL; p_list->p_tail = NULL; p_list->size = 0; } else if ( p_list->size > 1 ) { // Store a pointer to the first node node_t *p_to_delete = p_list->p_head; // Update the linked list p_list->p_head = p_list->p_head->p_next; --( p_list->size ); // Deallocate memory for the previous first node free( p_to_delete ); } } node_t *find( linked_list_t *p_list, int sought_value ) { node_t *p_node; for ( p_node = p_list->p_head; p_node != NULL; p_node = p_node->p_next ) { if ( p_node->value == sought_value ) { break; } } return p_node; }