链表错误无限循环
Linked List Error-Infinite Loop
我正在构造一个带有display()
和add_at_end()
函数的简单linked list
。以下是我的代码
#include<stdio.h>
#include<iostream>
using namespace std;
typedef struct node{
int num;
struct node *next;
}n;
n* head;
class ll{
public:
ll();
~ll();
void display();
void add_at_end(int n);
//void add_at_beginning(int n);
//int count();
//void delete_num(int n);
};
ll::ll(){
head=NULL;
}
ll::~ll(){
if(head!=NULL)
{
n *temp;
while(head!=NULL)
{
temp=head->next;
delete head;
head=temp;
}
}
}
void ll::display(){
if(head==NULL)
cout<<"There is nothing to display in the list";
else
{
n *temp;
temp=head;
while(temp!=NULL)
{cout<<temp->num;}
}}
void ll::add_at_end(int number)
{
n *temp=new n;
temp->num=number;
temp->next=NULL;
if(head==NULL)
head=temp;
else
{
n *tmp2;
tmp2=head;
while(tmp2!=NULL)
{ tmp2=tmp2->next;}
tmp2=temp;
}
}
int main(){
ll* fll=new ll();
fll->add_at_end(54);
fll->display();
return 0;
}
其他一切都很好,但是当我运行代码时,我得到一个无限循环,其中 54 一次又一次地被打印出来。我哪里犯了错误?在display()
函数还是add_at_end()
函数?
无限循环发生在显示中。 您没有前进临时指针
发现我的错误
在display()
函数中,循环I不是递增temp
变量。所以我将代码更改为
while(temp!=NULL)
{cout<<temp->num;
temp=temp->next;}
你还应该修复你的add_at_end函数:
while(tmp2->next != NULL)
{
tmp2 = tmp2->next;
}
tmp2->next = temp;
相关文章:
- 在分配和发布递增循环迭代器时C++无限循环(gcc 错误?
- 菜单驱动的逻辑错误导致无限循环
- CPP 在读取结构数据时无限循环错误?
- 如何修复关卡顺序遍历问题(二叉树)的无限循环错误
- 在 Linux 上C++的无限循环中捕获内存不足的错误 bad_alloc()
- C++ 输入字符而不是 int 会导致无限循环.如何检查错误的输入
- 错误:将元素加载到矢量时无限循环
- 链表错误无限循环
- 检查功能进入无限循环和分段错误
- 如果给出错误的输入,则无限循环
- 检查错误时重载>>运算符中的无限循环
- c++中的switchcase无限循环错误
- Qt 创建器错误无限循环
- 已经定义的错误和无限循环
- 我认为做而正在进入无限循环.或数组.(运行时错误)
- 在这段代码中查找3个错误,这些错误都会导致无限循环
- c++无限循环导致堆栈溢出错误
- 为什么当我按下一个字母时,会出现一个无限循环?我如何更改错误检查
- 什么可能导致无限循环错误
- std::cin无限循环错误输入