链表循环达到无穷大
linked list- loop goes to infinity
下面是我为创建和显示链表而编写的代码。我认为显示方法导致了无限循环的发生,但我无法找出原因。我与网上的代码进行了比较,看起来还可以。为什么会发生这种情况?
#include<iostream>
using namespace std;
class NODE
{
int data;
NODE*next;
NODE*start;
public:
NODE()
{
start=NULL;
}
void in(int v);
void display();
};
void NODE::in(int v)
{
NODE*n;
n=new NODE;
n->data=v;
n->next=NULL;
if (start==NULL)
{
start=n;
}
else
{
NODE*p;
p=start;
while(p->next!=NULL)
{
p=p->next;
}
p->next=n;
}
cout<<"leaving the insert function";
delete n;
}
void NODE::display()
{
cout<<"enters the display function";
NODE*p;p=start;
cout<<"data is-"<<'n';
while(p!=NULL)
{
cout<<p->data<<"->";
p=p->next;
}
}
int main()
{
NODE ob;
cout<<"enter the no. of values";
int h;
cin>>h;
for(int i=0;i<h;i++)
{
cout<<"enter the value to be inserted";
int v;
cin>>v;
ob.in(v);
}
ob.display();
return 0;
}
您在in
方法中delete
n
,如果您想使用该对象,您应该稍后执行。
此外,您对p->next
进行迭代,但该值从未初始化,因此即使对于新对象,它也肯定不会是NULL
!
您的display
方法看起来不错。
也许您应该添加一个LinkedList
类来管理所有节点,而正是这个对象关心添加一个新节点。
相关文章:
- 如何循环打印顶点结构
- 如何在C++中从两个单独的for循环中添加两个数组
- C++我的数学有什么问题,为什么我的代码不能正确循环
- 正在尝试了解输入验证循环
- std::map<struct,struct>::find 找不到匹配项,但是如果我循环通过 begin() 到 end(),我在那里看到匹配项
- 循环后如何继续阅读
- Ardunio UNO解决了多个重叠的定时器循环
- Eigen如何在容器循环中干净地附加矩阵
- 在某些循环内使用vector.push_back时出现分段错误
- 我正在使用嵌套的while循环来解析具有多行的文本文件,但由于某种原因,它只通过第一行,我不知道为什么
- 为什么我的for循环不能正确获取argv
- 如何声明特征矩阵,然后通过嵌套循环初始化它
- while循环中while循环的时间复杂度是多少
- 无穷大而循环时具有递归函数
- Matlab 如何知道有一个 .mex64 文件并避免无穷大"compiling"循环
- MIPS :循环进入无穷大
- unsigned int导致循环为无穷大
- 链表循环达到无穷大
- 而当 CIN 的输入是'dot'时循环到无穷大
- 开关内部的循环变为无穷大