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

C++自定义LinkedList类调用getNext返回空值问题求助

问题原因

  • 单参数构造函数未初始化next指针:你调用LinkedList(int valueIn)创建list1时,仅完成了value的赋值,next指针是未初始化的野指针,后续调用list1.getNext()对野指针解引用属于未定义行为,会出现输出异常、程序崩溃等问题。你调试时看到list2的value为2是正常的,但你访问的是list1野指针指向的随机内存,和list2本身没有关联,自然拿不到对应的值。
  • 链表指向逻辑完全反向:你初始化list2(2, &list1)时,是把list2的next指针指向了list1,但你预期的输出1 --> 2对应的逻辑是list1的next指向list2,两者完全相反。

修正代码

#include <iostream>
using namespace std;

class LinkedList {
  int value;
  LinkedList* next;

  public:
    LinkedList(int valueIn, LinkedList* nextIn) {
      value = valueIn;
      next = nextIn;
    }
    // 补充next指针初始化,默认置空
    LinkedList(int valueIn) {
      value = valueIn;
      next = nullptr;
    }

    int getValue() {
      return value;
    }

    void addNode(LinkedList* node) {
      next = node;
    }

    LinkedList* getNext() {
      // 返回指针更安全,方便外部判断节点是否为空
      return next;
    }
};

int main() {
  cout << "starting..." << std::endl;
  LinkedList list1(1);
  LinkedList list2(2);
  // 调整指向:list1的下一个节点为list2
  list1.addNode(&list2);
  cout << list1.getValue() << " --> " << list1.getNext()->getValue() << std::endl;
  return 0;
}

运行修正后的代码即可输出预期结果1 --> 2。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.03 08:18:03