#include "Single_list.h" /* * init_sl( ... ) * * Initialize the singly linked list by setting * 1. 'head' and 'tail' to NULL * 2. 'count' to 0 */ void init_sl( Single_list *this ) { this->head = NULL; this->tail = NULL; this->count = 0; } /* * destroy_sl * * To free the memory for the nodes, we will repeatedly * call pop_front on this list until it is empty. */ void destroy_sl( Single_list *this ) { while ( !empty( this ) ) { pop_front( this ); } } /* * init_sn * * Initialize a node by setting assigning the * fields the corresponding arguments. */ void init_sn( Single_node *this, int v, Single_node *n ) { this->value = v; this->next = n; } /* * empty * * A list is empty if the field 'count' is 0. */ int empty( Single_list *this ) { return ( this->count == 0 ); } /* * size * * The size of the list (the number of nodes in the list) * is stored by the field 'count' */ int size( Single_list *this ) { return this->count; } /* * front * * The front entry of the list is the field 'value' stored in * the first node pointed to by the field 'head' */ int front( Single_list *this ) { if ( empty( this ) ) { exit( -1 ); } return this->head->value; } /* * back * * The front entry of the list is the field 'value' stored in * the first node pointed to by the field 'tail' */ int back( Single_list *this ) { if ( empty( this ) ) { exit( -1 ); } return this->tail->value; } /* * push_front * * Steps: * 1. Allocate memory for a new node * 2. Initialize it with the argument and the current value of 'head' * 3. Update the field 'head', and if necessary, update 'tail' * 4. Increment the count */ void push_front( Single_list *this, int v ) { Single_node *ptr = malloc( sizeof( Single_node ) ); init_sn( ptr, v, this->head ); this->head = ptr; if ( this->tail == NULL ) { this->tail = ptr; } ++this->count; } /* * push_back * * If list is empty, just call push_front(); otherwise * * Steps: * 1. Update the 'next' field of the last node * 2. Initialize that new node with the the argument and 'NULL' * 3. Update the field 'tail' * 4. Increment the count */ void push_back( Single_list *this, int v ) { if ( empty( this ) ) { push_front( this, v ); return; } this->tail->next = malloc( sizeof( Single_node ) ); init_sn( this->tail->next, v, NULL ); this->tail = this->tail->next; ++this->count; } /* * pop_front * * If list is empty, signal an error; otherwise * * Steps: * 1. Temporarility store the return value * 2. Get a pointer to the node to be freed * 3. Update the field 'head' to point to the next node * 4. If 'head' now points to NULL, update the field 'tail' * 5. Decrement the count */ int pop_front( Single_list *this ) { if ( empty( this ) ) { exit( -1 ); } int return_value = this->head->value; Single_node *ptr = this->head; this->head = this->head->next; free( ptr ); if ( this->head == NULL ) { this->tail = NULL; } --this->count; return return_value; }