我们如何显示链接列表

How do we display a linked list?

本文关键字:链接 列表 显示 何显示 我们      更新时间:2023-10-16

,所以我创建了以下代码,但是显示功能给了我问题。每次我尝试使用它时,它都会变成无限的循环。有人可以看看它,告诉我出了什么问题吗?

#include<iostream.h>
#include<conio.h>
struct node{
    int info;
    node *next;
    }*ptr,*start,*temp;
node* create_new()
    {
    ptr=new node;
    cout<<"nEnter the data: ";
    cin>>ptr->info;
    ptr->next=NULL;
    return ptr;
    }

void insert_at_beg()
{
ptr=create_new();
if(start==NULL)
        {
    start=ptr;
    }
if(start!=NULL)
    {
    ptr->next=start;
    start=ptr;
    }
}
void display()
{
temp=start;
while(temp->next!=NULL)
    {
    cout<<"t"<<temp->info;
    temp=temp->next;
    }
}
void insert_at_end()
{
    if(start==NULL)
    {
    start=ptr;
    }
if(start!=NULL)
    {
    ptr=create_new();
    temp=start;
    while(temp->next!=NULL)
        {
        temp=temp->next;
        }
    temp->next=ptr;
    }
}
void delete_from_end()
{
if(start==NULL)
    {
    cout<<"NULL LL";
    }
else
    {
    temp=start;
    while(temp->next!=NULL)
        {
        ptr=temp;
        temp=temp->next;
        }
    ptr->next=NULL;
    delete temp;
    }
}

void delete_from_beg()
{
if(start==NULL)
    cout<<"nNULL LL";
else
    start=start->next;
}
void delete_from_mid()
{
int el;
if(start==NULL)
    {
    cout<<"nNULL LL";
    }
else
    {
    cout<<"nEnter element that you want to delete: ";
    cin>>el;
    temp=start;
    while(temp->next!=NULL&&temp->info!=el)
        {
        ptr=temp;
        temp=temp->next;
        }
    ptr->next=temp->next;
    delete temp;
    }
}


void main()
{
clrscr();
start=NULL;
temp=NULL;
ptr=NULL;
insert_at_beg();
display();
getch();
}

您的错误在此代码中:

void insert_at_beg()
{
  ptr=create_new();
  if(start==NULL)
  {
    start=ptr;
  }
  if(start!=NULL)
  {
    ptr->next=start;
    start=ptr;
  }
}

start中的第一次将是无效的,因此您将进行start=ptr。但是,现在if(start!=NULL)是正确的,因此您将进行ptr->next=start。由于ptrstart都指向相同的东西,您会创建一个无限的循环。

首先,我不建议您使用全局变量,尤其是当您拥有同一类型(和值)的函数时。

我的问题在于函数insert_at_beg():

// yes start is NULL initially
if(start==NULL)
        {
    start=ptr; // now start is not NULL!!
    }
//This statement will also be entered.
if(start!=NULL)
    {
    ptr->next=start;
    start=ptr;
    }
}

而是使用else

if(start==NULL)
        {
    start=ptr; // now start is not NULL!!
    }
else
    {
    ptr->next=start;
    start=ptr;
    }
}

另外,而不是:

#include<iostream.h>
#include<conio.h>

仅使用#include<iostream>

导致无限循环在其他地方的错误(insert_at_beg(),我在代码中看到有人已经添加了详细信息,所以我也不会这样做)。

您的代码仍然有问题:

void display()
{
    temp=start;
    while(temp->next!=NULL)
    {
    cout<<"t"<<temp->info;
    temp=temp->next;
    }
}

您不会打印最后的Enlemt。当当前元素的下一个(临时)为空时,您会停止。将其更改为

while(temp) // equivalent to while(temp !=NULL)

您的display功能可以简化:

void display()
{
  node * p = start;
  while (p != NULL)
  {
    cout << "t" << p->info;
    p = p->next;
  }
  cout << endl;  // The side effect of this is to print blank line when empty list.
}