c++ - 链表类

标签 c++ linked-list

好吧,我知道这是一个非常简单的问题,但出于某种原因,我无法使用链表。可能只是因为我真的很累,因为我以前已经做过一百万次了。将我的程序归结为尽可能最简单的实现,但仍然无法正常工作。

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

main.cpp

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

最佳答案

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

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() {}

关于c++ - 链表类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13331123/

相关文章:

c++ - Variadic 函数包装器无法使用 MSVC2017 进行编译

c++ - 声明不能解决 'explicit specialization after instantiation' 错误

java - 如何在我的 Java GUI 中使用 linkedList 和多个类

c - 比较 C 中链表中的值时出现问题

c++ - 从 MySQL 中检索 xml

c++ - 在函数声明中使用 ->

c++ - C++中长表达式的优化

c++ - 将指针设置为 NULL 会影响您指向的原始项目吗?

c# - 获取 LinkedList<T> 的第一个元素

java - 是否可以创建嵌套的 LinkedObject [Java]