|
A chain can be created by including an reference variable in the object itself |
How to create a linked list in which each element in the list can store one integer value
Step 1: define the right type of variables to realise the linked list
ListElem class provide necessary information to make linked list of integers
class ListElem { public: int value; // Integer ListElem *next; // Pointer used to make link }; |
Step 2: how to link one element to another
Instructions to create a "link" from obj1 to obj2
ListElem obj1; ListElem obj2; obj1.next = &obj2; obj2.next = NULL; // 0 is special ("end") |
Pictorially, this is what is going on inside the computer:
ListElem head; // a reference variable that points // to the first real element in // a linked list |
head = NULL; |
This is a "natural" consequence from the fact that the information necessary to access the ith element of the list (which is the location (address)) is stored in the i-1th element....
From the first element, we find the location (through the pointer variable) of the next element; and so on.
// Assume: head points to the first ListElem... ListElem *p; // Auxiliary pointer variable to traverse list p = head; // Very important: start at first element while ( p != NULL ) { cout << p->value; // Access value stored in list element p = p->next; // Visit next element in list } |
We will discuss these next...