链表循环达到无穷大

linked list- loop goes to infinity

本文关键字:无穷大 循环 链表      更新时间:2023-10-16

下面是我为创建和显示链表而编写的代码。我认为显示方法导致了无限循环的发生,但我无法找出原因。我与网上的代码进行了比较,看起来还可以。为什么会发生这种情况?

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

您在in方法中delete n,如果您想使用该对象,您应该稍后执行。

此外,您对p->next进行迭代,但该值从未初始化,因此即使对于新对象,它也肯定不会是NULL

您的display方法看起来不错。

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