取消下一个节点的空链接列表的头

Dereferencing head of empty linked list for next node

本文关键字:列表 链接 节点 取消 下一个      更新时间:2023-10-16

我试图在C 中实现链接列表,当我想到这个想法时。标准节点定义为

class node {
public:
    int data;
    node *next;
};

我创建了一个空列表node *head;,然后尝试了此

if(head->next == nullptr)
    cout<<"Stores nullptr";
if(! head->next)
    cout<<"Returns bool values";

但是没有输出,那么head->next中存储了什么?

首先,您应该在main中为节点类创建一些空间/分配内存。

请注意 node *head;只是声明而不是定义。有关更多细节,请查看定义和声明之间有什么区别?

  1. 您为对象分配空间
  2. 初始化其值,更优雅地定义构造函数方法
    node *head = new node;
    head->next = nullptr;
    head->data=0;

我仍然将其视为C

中链接列表的重复

如果您声明node *head;,则HEAD是包含随机地址的非初始化指针。提出它是不确定的行为

您需要a(初始化头: node *head = nullptr;,b(测试该条件: if (head == nullptr) { head = new node; node->head = nullptr; ...