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

gr3*_*bo1 4 c++ linked-list while-loop

通过定义存储单元

struct node {
    int item;
    node *next;
};
Run Code Online (Sandbox Code Playgroud)

假设ptr指向一个链表,那么put while(ptr!=NULL) while(ptr->next!=NULL)循环通过列表之间是否有区别,直到到达空指针?

Nat*_*pel 14

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

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

  • ...如果(且仅当)最后一个节点是一个发送者,这是有用的. (3认同)

Pie*_*aud 6

while(ptr != NULL)while(ptr->next != NULL)跳过最后一个元素时将迭代所有链表.

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