#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"; } /* ----------------------------------------------------------- InsertAtTail: insert elem at start of linked list Question: what would happen if we pass "head" by value ? ----------------------------------------------------------- */ void InsertAtTail(ListElem * & head, ListElem * elem) { ListElem *lastElem; if ( head == NULL ) // Detect and handle exception case.... { head = elem; elem->next = NULL; } else { // Find the last element in the list lastElem = head; while (lastElem->next != NULL) lastElem = lastElem->next; // Link "elem" to lastElem: lastElem->next = elem; // Mark new elem as the last element: elem->next = NULL; } } int main(int argc, char *argv[]) { ListElem *head, *p; void Print(ListElem *); void InsertAtTail(ListElem * &, ListElem *); head = NULL; Print(head); p = new ListElem; p->value = 1500; InsertAtTail(head, p); Print(head); p = new ListElem; p->value = 2500; InsertAtTail(head, p); Print(head); p = new ListElem; p->value = 3500; InsertAtTail(head, p); Print(head); }