This is a piece of code that tries to build a linked list.
struct node {
char name[20];
int age;
int height;
node* next; // Pointer to the next node
};
node* startPTR = NULL;
void addNode_AT_END() {
node *temp1;
node *temp2;
temp1 = new node;
cout << "Enter the name : ";
cin >> temp1->name;
cout << endl << "Enter the age : ";
cin >> temp1->age;
cout << endl << "Enter height : ";
cin >> temp1->height;
temp1->next = NULL;
if( startPTR == NULL) {
startPTR = temp1;
} else {
temp2 = startPTR;
while( temp2->next != NULL )
temp2 = temp2->next;
temp2->next = temp1;
}
}
The following is diagram after 2 back to back calls to the above function.
start = addr1;
|
V
(addr1) ----> (addr2) ----> (NULL) at end
^
|
temp2
where addr1 and addr2 are the address of the first and second nodes respectively.
What happens after the third call ? How the iteration will go on for the third call? I am unable to understand how the list links up after the second call.According to me all that has been build up till know will vanish.Then how will list move further ? How is node placed during the third call?
Here is where all the magic happens:
First,
temp2will point to the beginning of the list. In lines 2 and 3, you changetemp2to the next node until you reach the node wheretemp2->nextisNULL. This node is the last node of the list, regardless of the size of the list.Finally, in line 4 you change
temp2->nexttotemp1so now it points to the new node (that is last node now points to the new node).temp1->nextis alsoNULL, sotemp1now represents the end of the list.After line 1 you have
temp2->nextis notNULL(it is addr2), so you iterate and execute line 3 and you get:temp2->nextis nowNULL. So you stop the loop and execute line 4 and you get:Note: Do you know how pointers work? Imagine this: You have a node, which is some data in the memory. When you have variables in memory, these variables have addresses. Let’s say addr1 is 10, addr2 is 150 and addr3 (which is the node just
newed) is 60.starthas value 10. Therefore, “pointing” to the first node of the list (that is using this address, you have access to its data). One of these data, is thenextfield. The first node’snextfield has value 150, thus pointing to the next node. When you saytemp2 = start, you put number 10 intemp2, at this pointtemp2->nexthas value 150. When you saytemp2=temp2->next, you simply put value 150 intemp2, overwriting the previous value. This way you have effectively moved your pointer from pointing to the first node, to now pointing to the second node. Nowtemp2->nextisNULL(that is 0). When you now saytemp2->next=temp1, you put value 60 in thenextfield oftemp2. So nowtemp2->nextis 60.temp2->next->nextisNULL.