#include #include struct Node { int item; struct Node *next; }; void printList(struct Node *p); struct Node *addFirst(struct Node *h, int x); struct Node *removeLast(struct Node *h); int main() { struct Node *head = NULL; int k; // Insert for (k = 1; k < 10; k++ ) { head = addFirst(head, k); // printList(head); } // Delete printList(head); for (k = 1; k < 10; k++ ) { head = removeLast(head); printList(head); } } // Remove the last node from the list at h struct Node *removeLast(struct Node *h) { if ( h == NULL ) return NULL; // Return NULL if ( h->next == NULL ) { free(h); // De-allocated deleted node return NULL; // Return NULL } struct Node *current = h; struct Node *previous = h; while( current->next != NULL ) // Find the last node { previous = current; current = current->next; // Advance to next node } previous->next = NULL; // Unlink the last node (from its predecessor) free(current); // De-allocate deleted node return h; // Return (confirm first node was unchanged) } // Inserts a new node containg x // at the beginning of the list at h struct Node *addFirst(struct Node *h, int x) { struct Node *newNode = malloc( sizeof(struct Node) ); newNode->item = x; // Store x newNode->next = h; // Make it point to h return newNode; } void printList(struct Node *p) { while ( p != NULL ) { printf("%d -> ", p->item); p = p->next; } printf("[NULL]\n"); }