C++ 简单链表插入不起作用
我正在为单链表编写代码,在编写其插入函数时遇到了问题。它不是插入新节点,也不是打印它们。我找不到问题所在。任何帮助都将不胜感激 代码:C++ 简单链表插入不起作用,c++,linked-list,C++,Linked List,我正在为单链表编写代码,在编写其插入函数时遇到了问题。它不是插入新节点,也不是打印它们。我找不到问题所在。任何帮助都将不胜感激 代码: #包括 使用名称空间std; 类节点{ int数据; 节点*下一步; 公众: 节点(整数数据) { 数据=数据; next=nullptr; } 空白插入(内部编号) { 节点*索引=此->下一步; while(索引!=nullptr) { 索引=索引->下一步; } 索引=新节点(否); } 作废打印() { Node*index=this; while(索引
#包括
使用名称空间std;
类节点{
int数据;
节点*下一步;
公众:
节点(整数数据)
{
数据=数据;
next=nullptr;
}
空白插入(内部编号)
{
节点*索引=此->下一步;
while(索引!=nullptr)
{
索引=索引->下一步;
}
索引=新节点(否);
}
作废打印()
{
Node*index=this;
while(索引!=nullptr)
{
下一步是收集数据;
}
}
};
int main()
{
节点*头=新节点(1);
头部->插入(2);
头部->插入(3);
头部->插入(4);
头部->插入(5);
打印头->打印();
系统(“暂停”);
返回0;
}
谢谢以下是修复代码的一种方法:
class Node{
int data;
Node * next;
public:
Node(int data_, Node *ptr=nullptr) : data(data_), next(ptr) {}
void insert(int no) { next = new Node(no, next); }
void print() {
cout << data;
if (next != nullptr)
next->print();
}
};
在我看来,您似乎试图在列表的末尾插入新项目。您的
插入中有一个小错误
以下是一个应该有效的版本:
void insert(int no)
{
Node* index = this;
while (index->next != nullptr)
{
index = index->next;
}
index->next = new Node(no);
}
代码中错误的解释
void insert(int no)
{
Node * index = this->next;
// When there is only one item in the linked list, which is true when
// you are trying to insert the second item, index gets set to NULL.
// The while loop does not get executed.
while (index != nullptr)
{
index = index->next;
}
// index points to the newly created node but 'this' has no link
// with index. As a consequence, 'this' never gets the second item appended
// at the end.
index = new Node(no);
}
你为什么把你的名单放在最前面?或者这应该是第一个链接的初始化,在这种情况下,一个更统一的接口是一个好主意?您需要为next
分配一些内容,而不是临时索引。另外,通常会将节点
与列表
分开。感谢它工作正常,您能告诉我我的代码有什么问题吗。它看起来与您的类似,但不起作用。@FarazAhmad我扩展了我的答案,试图解释代码中的错误。
void insert(int no)
{
Node* index = this;
while (index->next != nullptr)
{
index = index->next;
}
index->next = new Node(no);
}
void insert(int no)
{
Node * index = this->next;
// When there is only one item in the linked list, which is true when
// you are trying to insert the second item, index gets set to NULL.
// The while loop does not get executed.
while (index != nullptr)
{
index = index->next;
}
// index points to the newly created node but 'this' has no link
// with index. As a consequence, 'this' never gets the second item appended
// at the end.
index = new Node(no);
}