You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C++链表代码疑问:打印空指针错误与节点连接问题求解

C++链表问题解答及修正代码

问题1:循环内访问正常,循环外空指针错误的原因

  • 大概率是你在printout函数里直接修改了成员变量this->first,没使用临时指针遍历链表。比如你的原代码可能是这么写的:
void printout() {
    while(this->first) {
        cout << this->first->new_data << endl;
        this->first = this->first->next; // 这里把first指针往后移了
    }
}
  • 循环过程中,this->first会一直往后挪,直到指向链表末尾的nullptr。循环结束后再去访问this->first->new_data,自然会触发空指针错误。而循环里每次访问前都通过while(this->first)判断了指针不为空,所以不会出问题。

问题2:误以为未连接第一个节点但输出正确的原因

  • 这通常是因为你添加第一个节点时,实际已经把first指针正确指向了该节点,只是自己对逻辑的理解有偏差。比如典型的链表插入逻辑:
void add(int data) {
    Node* new_node = new Node(data);
    if(this->first == nullptr) {
        this->first = new_node; // 这里已经把第一个节点和头指针连起来了
    } else {
        // 找尾节点插入新节点
        Node* curr = this->first;
        while(curr->next) curr = curr->next;
        curr->next = new_node;
    }
}
  • 插入第一个节点时,first是空的,直接让它指向新节点,此时链表头指针已经和第一个节点关联上了,后续遍历自然能输出正确结果,只是你误以为没连接而已。

修正后的完整示例代码

#include <iostream>
using namespace std;

// 链表节点结构
struct Node {
    int new_data;
    Node* next;
    Node(int data) : new_data(data), next(nullptr) {}
};

// 链表类
class LinkedList {
private:
    Node* first; // 链表头指针
public:
    LinkedList() : first(nullptr) {}
    
    // 向链表尾部添加节点
    void add(int data) {
        Node* new_node = new Node(data);
        if(first == nullptr) {
            first = new_node; // 第一个节点直接绑定头指针
        } else {
            Node* curr = first;
            // 遍历到尾节点
            while(curr->next != nullptr) {
                curr = curr->next;
            }
            curr->next = new_node;
        }
    }
    
    // 遍历输出链表,用临时指针保护头指针
    void printout() {
        Node* curr = first; // 用临时指针遍历,不修改原头指针
        while(curr != nullptr) {
            cout << curr->new_data << " ";
            curr = curr->next;
        }
        cout << endl;
    }
    
    // 安全访问第一个节点(循环外)
    void access_first_node() {
        if(first != nullptr) {
            cout << "第一个节点的数据:" << first->new_data << endl;
        } else {
            cout << "链表是空的,没法访问第一个节点!" << endl;
        }
    }
    
    // 析构函数,释放链表内存
    ~LinkedList() {
        Node* curr = first;
        while(curr != nullptr) {
            Node* temp = curr;
            curr = curr->next;
            delete temp;
        }
        first = nullptr;
    }
};

int main() {
    LinkedList myList;
    myList.add(10);
    myList.add(20);
    myList.add(30);
    
    cout << "链表内容:";
    myList.printout();
    
    myList.access_first_node(); // 循环外安全访问第一个节点
    
    return 0;
}

内容的提问来源于stack exchange,提问作者AokDesu

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.11 14:45:27