listDemo.cpp // listDemo.cpp // A first example of a linked list #include struct listNode { int data; listNode *next; }; typedef listNode* nodePtr; void createList (nodePtr &); void printList (nodePtr); void insert (nodePtr &, int value); main() { nodePtr first; createList (first); printList (first); return 0; } void createList (nodePtr &root) { root = NULL; for (int k=1; k<=5; k++) insert (root, k); } void insert (nodePtr &root, int value) { nodePtr newNode; newNode = new listNode; newNode->data = value; newNode->next = root; root = newNode; } void printList (nodePtr temp) { while (temp != NULL) { cout << temp->data << " "; temp = temp->next; } cout << endl; } // listDemo.cpp // using a struct constructor #include struct listNode { int data; listNode *next; listNode(int, listNode *); }; listNode::listNode (int tempData, listNode *tempNext) : data(tempData), next(tempNext) { // all values initialized in initializer list } typedef listNode* nodePtr; void createList (nodePtr &); void printList (nodePtr); main() { nodePtr first; createList (first); printList (first); return 0; } void createList (nodePtr &root) { root = NULL; for (int k=1; k<=5; k++) root = new listNode (k, root); } void printList (nodePtr temp) { while (temp != NULL) { cout << temp->data << " "; temp = temp->next; } cout << endl; } APCS - C++, Lesson 32 (c)1998, ICT H.A.32.1