#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 Question: what would happen if we pass "head" by value ? ----------------------------------------------------------- */ void DeleteAtTail(ListElem * & head) { ListElem *p2; ListElem *p1; if ( head == NULL ) // Delete only from non-empty list { return; } else { if ( head->next == NULL ) { // Handle special case: List has 1 element delete head; // Deallocate space head = 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; } // Delete element following the "p1" element p1->next = NULL; delete p2; // Deallocate space } } } /* ----------------------------------------------------------- InsertAtHead: insert elem at start of linked list Question: what would happen if we pass "head" by value ? ----------------------------------------------------------- */ void InsertAtHead(ListElem * & head, ListElem * elem) { elem->next = head; // Make new list element points // to the start of "old list" head = elem; // Make "head" points to // the **new** starting object } int main(int argc, char *argv[]) { ListElem *head, *p; extern void Print(ListElem *); extern void InsertAtHead(ListElem * &, ListElem *); extern void DeleteAtTail(ListElem * &); head = NULL; Print(head); p = new ListElem; p->value = 1500; InsertAtHead(head, p); Print(head); p = new ListElem; p->value = 2500; InsertAtHead(head, p); Print(head); p = new ListElem; p->value = 3500; InsertAtHead(head, p); Print(head); // ========================================== Removing... DeleteAtTail(head); Print(head); DeleteAtTail(head); Print(head); DeleteAtTail(head); Print(head); DeleteAtTail(head); Print(head); }