Closed. This question is off-topic。它当前不接受答案。
                            
                        
                    
                
                            
                                
                
                        
                            
                        
                    
                        
                            想改善这个问题吗? Update the question,所以它是on-topic,用于堆栈溢出。
                        
                        5年前关闭。
                                                                                            
                
        
下面给出的是我为创建和显示链接列表所做的代码。我认为显示方法导致了无限循环的发生,但我无法弄清原因。我将其与在线提供的代码进行了比较,看起来还可以。为什么会这样呢?

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

}

最佳答案

您在delete方法中n in,如果要使用该对象,应稍后再做。

同样,您遍历p->next但此值从未初始化,因此即使对于新对象也肯定不会成为NULL

您的display方法看起来不错。

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

关于c++ - 链表循环达到无穷大,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/25679608/

10-15 01:37
查看更多