我们如何显示链表?

时间:2014-02-01 17:06:21

标签: c++

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

#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();
}

4 个答案:

答案 0 :(得分:0)

您的错误在此代码中:

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都指向相同的事物,因此您将创建无限循环。

答案 1 :(得分:0)

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

根据我的问题在函数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>

答案 2 :(得分:0)

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

您的代码仍有问题:

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

你不会打印最后一个元素。当下一个当前元素(temp)为NULL时停止。 将其更改为

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

答案 3 :(得分:0)

您的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.
}
相关问题