c++ - 链表中节点的作用是什么?
问题描述
我正在从头开始创建一个链接列表。这是代码。起初,我已经定义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;
}
}
解决方案
您的链接列表将是一个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,则为真。
推荐阅读
- python - 如果比较 numpy 数组的语句引发 ValueError
- javascript - 函数内的 axios.get()
- python - 根据另一列中的类 (1,2,3) 将 NaN 值替换为一列中的所需值
- node.js - Node 控制台上没有错误,但无法按 Id 获取数据 - MERN 堆栈
- asp.net-mvc - 为什么迁移在迁移文件已经存在并且数据库更新时重新创建
- javascript - .less 样式不会进入内置的 React 应用程序
- reactjs - POST 请求错误 - net::ERR_CERT_COMMON_NAME_INVALID
- java - Quarkus 使用 Mandrel 原生构建
- java - 通过使用带有.get(位置)的回收器视图适配器,我无法从回收器视图java中的edittext获取文本
- sybase - 在 aqua 数据工作室中调试过程时是否可以运行查询?