打印链表

时间:2015-01-03 15:39:56

标签: c++ linked-list

我正在尝试用C ++学习Linkedlist。我试图在列表中插入新节点并显示它们。 但是在显示链接列表时,我得到了一些随机值。程序继续运行,并且根本没有停止。

#include<iostream>
using namespace std;
struct node
{
  int data;
  node *next;
};

int main()
{
  int ch;
  char ch1;
  do
  {

    cout<<"Enter your choice"<<endl;
    cout<<"1.Adding the first node"<<endl;
    cout<<"2.Adding a new node"<<endl;
    cout<<"3.Printing the list"<<endl;
    cin>>ch;
    node *n;
    node *t;
    node *h;
    switch(ch)
    {
      case 1:
        n=new node;
        int x;
        cout<<"Enter the value"<<endl;
        cin>>x;
        n->data=x;
        t=n;
        h=n;
        cout<<"Do you want to continue";
        cin>>ch1;
        break;

      case 2:
        n=new node;
        int y;
        cout<<"Enter the value"<<endl;
        cin>>y;
        n->data=y;
        t->next=n;
        t=t->next;
        cout<<"Do you want to continue";
        cin>>ch1;
        break;

      case 3:
        do
        {   while(h->next!=NULL)
          {


            cout<<h->data<<endl;
            h=h->next;
          }
        }while(h!=NULL);
        break;
    }
  }while(ch1=='y' || ch1=='Y');
}

2 个答案:

答案 0 :(得分:0)

您忘记为第一个节点设置为null:

case 1:
n=new node;
n->next = NULL;//this
int x;
cout<<"Enter the value"<<endl;
cin>>x;
n->data=x;
t=n;
h=n;
n->
cout<<"Do you want to continue";
cin>>ch1;
break;

以及最后一个节点:

case 2:
n=new node;
int y;
cout<<"Enter the value"<<endl;
cin>>y;
n->data=y;
n->next=NULL;//here too
t->next=n;
t=t->next;

cout<<"Do you want to continue";
cin>>ch1;
break;

答案 1 :(得分:0)

除此之外,您正在遍历头指针h=h->next;以显示值,因此如果您尝试第二次显示列表,它将不会显示任何内容。 而是遍历头指针使用临时指针并且还改变条件 while(h->next!=NULL)while(t!=null)以显示列表中的最后一个元素

t=h;

while(t!=NULL)
{
    cout<<t->data<<endl;
    t=t->next;
}