在C ++中实现链接列表

时间:2018-11-08 10:37:40

标签: c++ singly-linked-list

此代码仅打印30条错误信息

我已经遵循了本教程 https://www.codementor.io/codementorteam/a-comprehensive-guide-to-implementation-of-singly-linked-list-using-c_plus_plus-ondlm5azr

我不知道如何打印30张?这段代码有什么问题吗?

#include <iostream>

using namespace std;

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

class LinkedList {
    private:
        node *head, *tail;

    public:
        LinkedList() {
            head = NULL;
            tail = NULL;
        }

        // For adding nodes
        void addNode(int value) {
            node *tmp = new node;
            tmp->data = value;
            tmp->next = NULL;

            if(head == tail) {
                head = tmp;
                tail = tmp;
                tmp = NULL;
            } else {
                tail->next = tmp;
                tail = tail->next;
            }
        }

        // For displaying nodes
        void display() {
            node *tmp = head;

            while(tmp != NULL) {
                cout << tmp->data << endl;
                tmp = tmp->next;
            }
        }
};

int main()
{
    LinkedList a;

    // For adding nodes
    a.addNode(10);
    a.addNode(20);
    a.addNode(30);

    // For displaying nodes
    a.display();

    return 0;
}

2 个答案:

答案 0 :(得分:2)

if条件始终返回true:

if(head == tail) {

在第一次插入时它会返回true,因为head和tail是NULL。在第二次插入时,此条件也返回true,因为头和尾是相同的,依此类推。因此,您无需添加新项目,但始终会覆盖第一个项目。

您应通过

对其进行修复
 if (head == NULL)

答案 1 :(得分:0)

我认为错误发生在if(head == tail)行,如果将其更改为if(head == NULL),则应打印10 2030。但是,如果您想知道为什么if(head == tail )导致此问题的原因是,对于每个ad​​dNode操作,头和尾都相等,最后头也下垂到30!