//////////////////////////////////////////////////////// // // liststrings.cpp // // Started by Jeff Ondich on 5/27/98 // Last modified 11/11/99 // // This program demonstrates pointers and linked // lists in C++ by considering linked lists of // characters. // //////////////////////////////////////////////////////// #include // A struct is a class whose member data and functions // are public by default. struct CharNode { char mData; CharNode* mNext; // An address of a CharNode }; // It's convenient to have a type to represent // a pointer to a node, in addition to the node // type itself. typedef CharNode * CharNodePtr; void ReadString( CharNodePtr& head ); void WriteString( CharNodePtr head ); void WriteStringBackwards( CharNodePtr head ); int main( void ) { // Initializing a pointer to 0 is how you // say "this linked list is empty now." CharNodePtr message = 0; cout << "Type something, please: "; ReadString( message ); cout << "You typed: "; WriteString( message ); cout << endl; cout << "Backwards: "; WriteStringBackwards( message ); cout << endl; return( 0 ); } //////////////////////////////////////////////////////// // ReadString reads a line of text from cin and // inserts it into a linked list whose first node is // pointed to by "head." //////////////////////////////////////////////////////// void ReadString( CharNodePtr& head ) { char c; CharNodePtr newNode; CharNodePtr previousNode; // If there's no string to read, make sure the // linked list is empty, and return. cin.get(c); if( !cin || c == '\n' ) { head = 0; return; } // If we've gotten to here, then we know there's at // least one character in the line, so we need to // create a node to put it in, and attach that // node to the front of the list. head = new CharNode; if( head == 0 ) { cout << "Memory allocation trouble. Bye." << endl; exit(0); } head->mData = c; head->mNext = 0; previousNode = head; // Now that we have a one-node list, we can do the // rest of the string in a loop. cin.get( c ); while( c != '\n' && !cin.fail() ) { newNode = new CharNode; if( newNode == 0 ) { cout << "Memory allocation trouble. See you." << endl; exit(0); } newNode->mData = c; newNode->mNext = 0; previousNode->mNext = newNode; previousNode = newNode; cin.get( c ); } } //////////////////////////////////////////////////////// // WriteString writes the given string to cout. // Note that no endl is written. //////////////////////////////////////////////////////// void WriteString( CharNodePtr head ) { CharNodePtr current = head; while( current != 0 ) { cout << current->mData; current = current->mNext; } } //////////////////////////////////////////////////////// // WriteStringBackwards writes the given string // to cout, backwards. Note that no endl is written. //////////////////////////////////////////////////////// void WriteStringBackwards( CharNodePtr head ) { if( head != 0 ) { WriteStringBackwards( head->mNext ); cout << head->mData; } }