Notice that the chain is contructed using references (i.e., addresses)
|
A link is created by including an reference variable in the object itself |
This is the class definition:
class ListElem { public: int value; // Integer ListElem *next; // Pointer used to make link }; |
ListElem obj1; ListElem obj2; obj1.value = 1000; obj2.value = 5000; |
In addition, the elements' value field have been initialized.
obj1.next = &obj2; |
obj2.next = NULL; // = 0, it means "end" |
This is what is going on inside the computer when you make a linked list:
Although the linked list is created, we (as the programmer) need information about the linked list to use it
|
(ListElem *) |
(ListElem *) head; head = &obj1; // Remember the start of the list |
head = NULL; |
visiting every element in the list |
While visiting the elements of the list, you can perform operation(s) on the elements.
E.g.: sum all the values stored in the list elements
|
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....
Starting from the first element of the list, we find the location (through the pointer variable) of the next element; and so on.
ListElem *head; // 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...