11.07.2015 Views

tYSR20

tYSR20

tYSR20

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Linking Up with Linked ListsChapter 14: Point and Stare at Objects 195The second most common structure after the array is called a list. Lists comein different sizes and types; however, the most common one is the linked list.In the linked list, each object points to the next member in a sort of chainthat extends through memory. The program can simply point the last elementin the list to an object to add it to the list. This means that the user doesn’thave to declare the size of the linked list at the beginning of the program —you can cause the linked list to grow (and shrink) as necessary by adding(and removing) objects.The cost of such flexibility is speed of access. You can’t just reach in andgrab the tenth element, for example, like you would in the case of an array.Now, you have to start at the beginning of the list and link ten times from oneobject to the next.A linked list has one other feature besides its run-time expandability (that’sgood) and its difficulty in accessing an object at random (that’s bad) — alinked list makes significant use of pointers. This makes linked lists a greattool for giving you experience in manipulating pointer variables.Not every class can be used to create a linked list. You declare a linkableclass as follows:class LinkableClass{public:LinkableClass* pNext;};// other members of the classThe key is using the pNext pointer to an object of class LinkableClass.At first blush, this seems odd indeed — a class contains a pointer to itself?Actually, this says that the class Linkable contains a pointer to anotherobject also of class Linkable.The pNext pointer is similar to the appendage used to form a chain of childrencrossing the street. The list of children consists of a number of objects,all of type child. Each child holds onto another child.The head pointer is simply a pointer of type LinkableClass*: To keep torturingthe child chain analogy, the teacher points to an object of class child.(It’s interesting to note that the teacher is not a child — the head pointer isnot of type LinkableClass*.)LinkableClass* pHead = (LinkableClass*)0;

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

Saved successfully!

Ooh no, something went wrong!