#include class ListElem { public: int value; // Integer ListElem *next; // Pointer used to make link }; void Print(ListElem *head) { ListElem *p; p = head; // Very important: start at first element cout << "List ==> "; while ( p != NULL ) { cout << p->value << " "; // Access value stored in list element p = p->next; // Visit next element in list } cout << "\n\n"; } /* ----------------------------------------------------------- DeleteAtTail: Delete elem at TAIL of linked list ----------------------------------------------------------- */ ListElem * DeleteAtTail(ListElem * head) { ListElem *p2; ListElem *p1; if ( head == NULL ) // Delete only from non-empty list { return(NULL); } else { if ( head->next == NULL ) { // Handle special case: List has 1 element delete head; // Deallocate space return(NULL); } else { // The general case // Find the last-but-one "p1" and last "p2" elements p1 = head; p2 = head->next; while ( p2->next != NULL ) { p1 = p2; p2 = p2->next; } p1->next = NULL; // Delete element following list delete p2; // Deallocate space return(head); } } } /* ----------------------------------------------------------- InsertAtHead: insert elem at start of linked list Function returns head of new linked list ----------------------------------------------------------- */ ListElem * InsertAtHead(ListElem * head, ListElem * elem) { elem->next = head; // Make new list element points // to the start of "old list" return(elem); // Return the new head } int main(int argc, char *argv[]) { ListElem *head, *p; void Print(ListElem *); extern ListElem *InsertAtHead(ListElem *, ListElem *); extern ListElem * DeleteAtTail(ListElem * head); head = NULL; Print(head); p = new ListElem; p->value = 1500; head = InsertAtHead(head, p); Print(head); p = new ListElem; p->value = 2500; head = InsertAtHead(head, p); Print(head); p = new ListElem; p->value = 3500; head = InsertAtHead(head, p); Print(head); // ========================================== Removing... head = DeleteAtTail(head); Print(head); head = DeleteAtTail(head); Print(head); head = DeleteAtTail(head); Print(head); head = DeleteAtTail(head); Print(head); }