链表错误无限循环

Linked List Error-Infinite Loop

本文关键字:无限循环 错误 链表      更新时间:2023-10-16

我正在构造一个带有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;