0

好的,我知道这是一个非常简单的问题,但由于某种原因,我无法让链接列表工作。可能只是因为我真的很累,因为我以前做过一百万次。将我的程序简化为最简单的实现,但仍然无法正常工作。

非常基本的实现,只需制作一个整数 LL,这是我之前做过一百万次的事情,但无论出于何种原因,它永远不会超过头脑。

主文件

#include <iostream>
#include "ll.h"
using namespace std;

int main()
{
    int x;
    list ll;
    int i =0;


    while(i == 0)
    {
    cout << "Enter a value to add to the LL ";
    cin >> x;

    ll.add(x);
    ll.display();
    }

return 0;
}

ll.h

struct node
{
    int val;
    node * next;
};

class list
{
    public:
    list();

    void add(int);
    void display();
    node * head;
};

ll.cpp

#include <iostream>
#include "ll.h"
using namespace std;

list::list()
{
    head = NULL;
}

void list::add(int x)
{
    if(!head)
    {
        cout << "First  " << endl;
        head = new node;
        head->val = x;
        head->next = NULL;
    }
    else
    {
        node * current = head;
        while (current)
            current = current->next;

        current = new node;
        current->val = x;
        current->next = NULL;

    }
}

void list::display()
{
    node * current = head;

    while(current)
    {
        cout << current->val << endl;
        current = current->next;
    }
}
4

2 回答 2

2

看来您想追加到列表中。在这种情况下,您的循环条件不应该是

while (current)

while (current->next)

确保最初是非 NULL (您可以通过检查 `head 来执行此操作)。

实际上,设置新节点的逻辑也不太对。您可能希望第二个分支add()看起来像这样:

while (current->next) {
    current = current->next;
}
current->next = new node(x);

...具有合适的构造函数node

node::node(int x): val(x), next() {}
于 2012-11-11T12:32:15.973 回答
1

除了 Dietmar 的回答之外,您还有一个不正确的 while 循环:

while ( i == 0 ) {
     ...
}

在 for 循环的主体中,i永远不会改变,导致它无限循环。我不完全确定你想用什么i

于 2012-11-11T12:36:29.850 回答