11.07.2015 Views

tYSR20

tYSR20

tYSR20

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Chapter 14: Point and Stare at Objects 199}// get the next entrypNDS = pNDS->pNext;}// wait until user is ready before terminating program// to allow the user to see the program resultssystem(“PAUSE”);return 0;Although somewhat lengthy, the LinkedListData program is simple if you takeit in parts. The NameDataSet structure has room for a person’s name and alink to the next NameDataSet object in a linked list. I mentioned earlier thatthis class would have other members in a real-world application.The main() function starts looping, calling getData() on each iteration tofetch another NameDataSet entry from the user. The program exits the loopif getData() returns a null, the “non-address,” for an address.The getData() function prompts the user for a name and reads in whateverthe user enters. The program just hopes that the number of characters is lessthan 128, since it makes no checks. If the string entered is equal to exit, thefunction returns a null to the caller, thereby exiting the while loop. Thestricmp() compares two strings without regard to case. If the string enteredis not exit, the program creates a new NameDataSet object, populates thename, and zeroes out the pNext pointer.Never leave link pointers uninitialized. Use the old programmer’s wives’ tale:“When in doubt, zero it out.” (I mean “old tale,” not “tale of an old wife.”)Finally, getData() returns the object’s address to main().main() adds each object returned from getData() to the beginning of thelinked list pointed at by the global variable pHead. Control exits the initialwhile loop when the getData() returns a null. main() then enters a secondsection that iterates through the completed list, displaying each object. Thesecond while loop terminates when it reaches the last object, the objectwith a pNext pointer whose value is null.The program outputs the names entered in the opposite order. This isbecause each new object is added to the beginning of the list. Alternatively,the program could have added each object to the end of the list — doing sojust takes a little more code.

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!