#include #include struct Node { int element; struct Node *next; }; struct List { struct Node *head; int count; }; // Initialize a new linked list: set the count to zero and the head pointer to NULL. void init( struct List *list ) { list->head = NULL; list->count = 0; } // Return the first element in the linked list. If the list is empty, return 0. int front( struct List *list ) { if ( list->count == 0 ) { return 0; } return list->head->element; } // Allocate memory for a new node storing the argument 'value' and setting its next // pointer to the address of the current head of the linked list, // then setting the head of the linked list to this new node and updating the count. void push( struct List *list, int value ) { struct Node *nd = malloc( sizeof( struct Node ) ); printf( "Allocating a new node at %p\n", nd ); nd->element = value; nd->next = list->head; list->head = nd; ++(list->count); // The parenthesis are not necessary, but it's much clearer } // If the linked list is empty, do nothing. // Otherwise, temporarily store a pointer to the current head, updating the // head of the linked list, decrement the count, and then free the memory // for the stored node. void pop( struct List *list ) { if ( list->count == 0 ) { return; } struct Node *nd = list->head; list->head = list->head->next; --(list->count); // The parenthesis are not necessary, but it's much clearer free( nd ); } // Clear the linked list by repeatedly calling 'pop' until the list is empty. void clear( struct List *list ) { while ( list->count != 0 ) { pop( list ); } } int main() { struct List *ls = malloc( sizeof( struct List ) ); printf( "Allocating a new linked list at %p\n", ls ); init( ls ); push( ls, 5 ); push( ls, 7 ); printf( "Current head: %d\n", front( ls ) ); printf( "Current count: %d\n", ls->count ); pop( ls ); printf( "Current head: %d\n", front( ls ) ); printf( "Current count: %d\n", ls->count ); clear( ls ); printf( "Current count: %d\n", ls->count ); free( ls ); return 0; }