首页 > 解决方案 > 赋值只在循环外有效

问题描述

我正在学习 CPP(第一语言),并且正在尝试反转链表。此代码不起作用

node* reverse(node** head){
    node* previous=NULL;
    node* current=*head;
    node* nextptr=current->next;
    while(current!=NULL){
        current->next=previous;
        previous=current;
        current=nextptr;
        nextptr=nextptr->next;
    }
    return previous;
}

这个正在工作

node* reverse(node** head){
    node* previous=NULL;
    node* current=*head;
    node* nextptr;
    while(current!=NULL){
        nextptr=current->next;
        current->next=previous;
        previous=current;
        current=nextptr;
    }
    return previous;
}

为什么第二个代码片段有效,而第一个无效?

标签: c++pointerslinked-listreversing

解决方案


为什么第二个代码片段有效,而第一个无效?

第一个片段在取消引用潜在的空指针之前不检查。因为您使用空指针来指示列表的结尾,所以它总是取消引用空指针,因此具有未定义的行为。

第二个片段永远不会取消引用它尚未验证为非空的指针。


推荐阅读