c++ - Why does the sub-function displayed in the linked list need to have a variable?
曾经蜡笔没有小新
曾经蜡笔没有小新 2017-05-16 13:29:38
0
2
613
void display(link head)
{
    link p;
    p=head;
    if(p==NULL)
    printf("\nlist is empty");
    else do
    {
        printf("%d",p->data);
        p=p->next;
        
    }while(p!=NULL);
 } 

The book says to think about why you should set head to p instead of using it directly. I don’t see why. Why?
link is the pointer of the linked list

曾经蜡笔没有小新
曾经蜡笔没有小新

reply all(2)
習慣沉默

head is four characters longer than p.
The meaning of head refers specifically to the head node, and the pointer used when traversing the linked list will point to each node of the linked list. The meaning of using head is inappropriate.

滿天的星座

@仁伟 has already mentioned one reason, because we do not want to use "head" to traverse the entire linked list.
In addition to this reason, I can also think of another reason, that is, we need to keep a copy of "head". In this function, we do not need to use "head" again, but for some other complex functions, we may want to use "head" after traversing the linked list. If we traverse the linked list directly using "head" instead of "p", we will no longer be able to access the head node. Therefore, we need to save a copy of "head", that is, use p = head, instead of directly using "head" to traverse.

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template