链表循环进入无穷大

时间:2014-09-05 06:12:14

标签: c++ linked-list infinite-loop

以下是我为创建和显示链表所做的代码。我认为显示方法导致无限循环发生,但我无法弄清楚原因。我与在线提供的代码进行了比较,看起来没问题。为什么会这样?

#include<iostream>

using namespace std;

class NODE
{
    int data;
    NODE*next;
    NODE*start;
public:
      NODE()
      {
          start=NULL;
      }
      void in(int v);
      void display();
};

void NODE::in(int v)
{
    NODE*n;
    n=new NODE;
    n->data=v;
    n->next=NULL;
    if (start==NULL)
    {
        start=n;
    }
    else
    {
        NODE*p;
        p=start;
        while(p->next!=NULL)
        {
            p=p->next;
        }
        p->next=n;

        }
        cout<<"leaving the insert function";
    delete n;
}

void NODE::display()
{   
    cout<<"enters the display function";
    NODE*p;p=start;
    cout<<"data is-"<<'\n';
    while(p!=NULL)
    {
        cout<<p->data<<"->";
        p=p->next;
    }
}
int main()
{
    NODE ob;
    cout<<"enter the no. of values";
    int h;
    cin>>h;
    for(int i=0;i<h;i++)
        {
            cout<<"enter the value to be inserted";
            int v;
            cin>>v;
            ob.in(v);
        }
    ob.display();
    return 0;

}

1 个答案:

答案 0 :(得分:4)

delete方法中的n in,如果您想使用该对象,请稍后再进行此操作。

此外,你迭代p->next,但这个值永远不会被初始化,所以即使对于一个新对象,它肯定不会是NULL

您的display方法看起来不错。

也许您应该添加一个LinkedList类来管理所有节点,而这个对象将关注添加新节点。