遍历链表:while(ptr!= NULL)vs while(ptr-> next!= NULL)?

时间:2013-09-16 19:34:12

标签: c++ while-loop linked-list

通过

定义存储单元
struct node {
    int item;
    node *next;
};

并假设ptr指向链接列表,将while(ptr!=NULL) while(ptr->next!=NULL)置于循环列表直到达到null之间是否存在差异指针?

2 个答案:

答案 0 :(得分:14)

while(ptr->next!=NULL)不会遍历您的最后一个节点。

当您到达最后一个节点时,ptr->next将为空,并且它将退出while循环

答案 1 :(得分:6)

while(ptr != NULL)跳过最后一个元素时,

while(ptr->next != NULL)将遍历您的所有链接列表。

当您想要访问最后一个节点以在列表末尾添加新元素时,第二个解决方案非常有用。