// ptr2.cpp // tom bailey 27 aug 08 // Simple use of pointers to form a linked list. // C-style, uses global functions instead of class methods. #include using std::cout; using std::endl; using std::cin; // A struct is a class with public default. struct Node { Node * next; // Construct a Node that references *theNext. Node( Node * theNext ) { next = theNext; } }; // Add a new Node to the beginning of the list referenced // by ptr. void addFirst( Node * & ptr ) { ptr = new Node( ptr ); } // Add a new Node to the end of the list referenced by ptr. void addLast( Node * & ptr ) { if( ptr == NULL ) { addFirst( ptr ); } else { Node * curr = ptr; Node * next = curr->next; while( next != NULL ) { curr = next; next = curr->next; } addFirst( curr->next ); } } // Print the addresses of the Nodes of the list referenced // by ptr. void printList( Node * ptr ) { if( ptr != NULL ) { cout << ptr << endl; printList( ptr->next ); } } // Return the number of Nodes in the list referenced by ptr. int listLength( Node * ptr ) { int length = 0; while( ptr != NULL ) { ++length; ptr = ptr->next; } return length; } // Destroy all the Nodes in the list referenced by ptr. void destroyList( Node * & ptr ) { while( ptr != NULL ) { Node * curr = ptr; ptr = ptr->next; delete curr; } } int main() { Node * start = NULL; cout << "list is" << endl; printList( start ); cout << "end of list" << endl << endl; addLast( start ); cout << "list is" << endl; printList( start ); cout << "end of list" << endl << endl; for( int i=0; i<4; ++i ) { addFirst( start ); } cout << "list is" << endl; printList( start ); cout << "end of list" << endl << endl; for( int i=0; i<4; ++i ) { addLast( start ); } cout << "list is" << endl; printList( start ); cout << "end of list" << endl << endl; cout << "list length is " << listLength( start ) << endl; cout << "How many more? "; int n = 0; cin >> n; for( int i=0; i