C++ 链表错误无限循环
我正在用display和add_-at_-end函数构建一个简单的链表。下面是我的代码C++ 链表错误无限循环,c++,linked-list,C++,Linked List,我正在用display和add_-at_-end函数构建一个简单的链表。下面是我的代码 #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
#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会一次又一次地打印出来。我哪里出错了?在显示功能或结束时添加功能中?发现了我的错误
在显示函数中,循环I不是增量温度变量。所以我把代码改成
while(temp!=NULL)
{cout<<temp->num;
temp=temp->next;}
无限循环发生在显示器上。您没有推进临时指针您还应该修复add_at_end函数:
while(tmp2->next != NULL)
{
tmp2 = tmp2->next;
}
tmp2->next = temp;
您可能希望更仔细地查看add_at_end函数中的循环。除此之外,我建议您在调试器中逐行遍历代码。这可能会帮助您将问题缩小到一个特定的函数,并可能自己解决它。