#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"; } /* ----------------------------------------------------------- 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 } /* ----------------------------------------------------------- DeleteAtTail: Delete elem at TAIL of linked list Question: what would happen if we pass "head" by value ? ----------------------------------------------------------- */ void DeleteAtTail(ListElem * & head) { ListElem *last; ListElem *last_but_one; if ( head != NULL ) // Delete only from non-empty list { if ( head->next == NULL ) { // Handle special case: List has 1 element last = head; // Save for delete operator head = NULL; delete last; // Use saved value to delete element } else { // The general case // Find the "last_but_one" element last_but_one = head; while ( last_but_one->next->next != NULL ) { last_but_one = last_but_one->next; } // Delete element following the "last_but_one" element last_but_one->next = NULL; } } } int main(int argc, char *argv[]) { ListElem *head, *p; void Print(ListElem *); void InsertAtHead(ListElem * &, ListElem *); 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); }