#include #include using namespace std; template class Node { public: ITEMTYPE cargo; Node* next; Node () { cargo = ITEMTYPE(); next = NULL; } Node (ITEMTYPE Cargo, Node* Next) { cargo = Cargo; next = Next; } }; /* template void printList (Node* list) { Node* node = list; while (node != NULL) { cout << node->cargo; node = node->next; } cout << endl; } */ template void printList(Node* list) { for (Node* node = list; node != NULL; node = node->next) { cout << node->cargo; } } template void prettyPrint (Node* list) { cout << '('; // print out elements Node* node = list; while (node != NULL) { cout << node->cargo; if (node->next != NULL) cout << ", "; node = node->next; } cout << ')'; } template void printBackward (Node* list) { if (list == NULL) return; Node* head = list; Node* tail = list->next; printBackward (tail); cout << head->cargo; } template void printBackwardNicely (Node* list) { cout << '('; if (list != NULL) { printBackward (list); } cout << ')'; } template Node* removeSecond (Node* list) { Node* first = list; Node* second = list->next; // make the first node refer to the third first->next = second->next; // separate the second node from the rest of the list second->next = NULL; return second; } template class LinkedList { public: int length; Node* head; LinkedList () { length = 0; head = NULL; } void printBackwardNicely () { cout << '('; if (head != NULL) { Node* tail = head->next; printBackward (tail); cout << head->cargo; } cout << ')'; } void addFirst (ITEMTYPE i) { Node* node = new Node (i, head); head = node; length++; } }; int main () { Node node = Node (1, NULL); cout << node.cargo << endl; Node* pnode = new Node (2, NULL); cout << (*pnode).cargo << endl; cout << pnode->cargo << endl; Node* pnode1 = new Node (1, NULL); Node* pnode2 = new Node (2, NULL); Node* pnode3 = new Node (3, NULL); cout << pnode1->cargo << pnode2->cargo << pnode3->cargo << endl; // (*pnode1).next = pnode2; pnode1->next = pnode2; pnode2->next = pnode3; pnode3->next = NULL; printList (pnode1); cout << endl; prettyPrint(pnode1); cout << endl; printBackward (pnode1); cout << endl; printBackwardNicely (pnode1); cout << endl; prettyPrint (pnode1); cout << endl; Node* removed = removeSecond (pnode1); prettyPrint (removed); cout << endl; prettyPrint (pnode1); cout << endl; LinkedList L; L.addFirst(7); L.addFirst(8); L.addFirst(9); L.printBackwardNicely(); cout << endl; LinkedList SL; SL.addFirst("first"); SL.addFirst("second"); SL.printBackwardNicely(); cout << endl; LinkedList M; int x; cin >> x; while (x >= 0) { M.addFirst(x); cin >> x; } M.printBackwardNicely(); cout << endl; cout << endl; return 0; }