首页 > 解决方案 > 链表中节点的作用是什么?

问题描述

我正在从头开始创建一个链接列表。这是代码。起初,我已经定义node *root=NULL;

这意味着根节点没有元素。但是当我附加第一个元素时,我必须创建root=new node();

不是node *root=NULL;已经创建了根节点吗?那为什么我必须使用root=new node();.

实际上我对node *root=NULL;& root=new node();& root==NULL'感到困惑。你能让我明白吗?

#include<bits/stdc++.h>
using namespace std;
struct node
{
    int roll;
    node *next;

};

node *root=NULL;

void append(int roll)
{
    if( root==NULL)
    {
        root=new node();
        root->roll=roll;
        root->next=NULL;

    }
    else
    {
        node *current_node=root;


        while(current_node->next!=NULL)

        {
            current_node=current_node->next;

        }
        node *newnode=NULL;
        newnode=new node();
        newnode->roll=roll;
        newnode->next=NULL;
        current_node->next=newnode;


    }
}

标签: c++linked-list

解决方案


您的链接列表将是一个nodes通过指针连接的列表。

如果您指定node *root = nullptr;,您将无法访问任何成员root。毕竟,root 不是指向一个节点,而是指向nullprt. root = new Node()使用默认构造函数创建一个新的 Node 元素。您现在将能够访问此元素的成员。这就是为什么root->rool并且root->next现在将起作用。

node *root: 声明 root 是指向 a 的指针node

root = NULL:对我来说似乎过时了,但会将指针分配给 nullprt

root = new node():将 root 分配给node使用默认构造函数创建的实例。

root == nullprt: 如果 root 是 nullptr,则为真。


推荐阅读