#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"; } /* ----------------------------------------------------------- DeleteAtHead: Delete elem at start of linked list ----------------------------------------------------------- */ ListElem * DeleteAtHead(ListElem * head) { ListElem *p2; if (head == NULL ) // Must make sure list is not empty return(NULL); p2 = head; // Delete p2 head = p2->next; delete p2; // Return memory !! 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 *); ListElem *InsertAtHead(ListElem *, ListElem *); 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); cout << endl; cout << "Delete head..." << endl; head = DeleteAtHead(head); Print(head); cout << "Delete head..." << endl; head = DeleteAtHead(head); Print(head); cout << "Delete head..." << endl; head = DeleteAtHead(head); Print(head); cout << "Delete head..." << endl; head = DeleteAtHead(head); Print(head); cout << "Delete head..." << endl; head = DeleteAtHead(head); Print(head); }