FAQC
FAQC
FAQ 1 :
What is the difference between
while(p!=NULL) ,
while(p->link!=NULL) and
while(p->link->link!=NULL) in linked lists?
When to use which one?
______________________________________________________________________________
p = start;
while(p!=NULL)
start
{ ………
p is NULL
p = p->link; }
When the loop condition is while(p!=NULL), the loop executes till p is not
NULL, it terminates when p becomes NULL.
So after the loop terminates, p will be NULL. We use this condition when we
want to visit each node of the list till the last node, for example when we have to
print values in all nodes or when we have to search for a value in the list. This
condition we have used in the previous lecture in traversal, where we had to
access info of all the nodes starting from first node till the last node.
………………………………………………………………………………..
When the loop condition is while(p->link!=NULL), the loop executes till
p->link is not NULL, it terminates when p->link becomes NULL. NULL is
present in the link of last node, so after this loop terminates p will point to the
last node.
We can use this loop when we want a pointer to last node of the list. We will
use it when we have to insert a new node after the last node because in that case
we need a pointer to the last node.
When you want to find pointer to last node, you don't want to stop the loop
when p becomes NULL, you want to stop it when p points to the last node. So
you have to write the condition while(p->link!=NULL). If you write
while(p!=NULL), then when the loop stops, p will be NULL.
FAQ 2:
Here is a doubt that comes up in the lecture on insertion, it is better to clarify
this point here only.
We have seen that this is the code for finding pointer to a node at particular
position.
p=start;
for(i=1; i<k && p!=NULL; i++)
p=p->link;
If k is 4, then after the above loop terminates, p will point to the fourth node.
start
p
1 2 3 4 5
p=start;
for(i=1; i<k-1 && p!=NULL; i++)
p=p->link;
We changed k to k-1 and this will give us pointer to predecessor of kth node.
We will need this pointer when we will insert a new node at the kth position in
the list.
start
1 2 3 4 5