繁体   English   中英

在 C++ 中实现链表

[英]Implementing a linked list in c++

这段代码只打印 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;
}

if条件总是返回真:

if(head == tail) {

第一次插入时它返回 true,因为 head 和 tail 是 NULL。 在第二次插入时,此条件也返回 true,因为 head 和 tail 相同,依此类推。 所以你不添加新项目,但你总是覆盖第一个项目。

你应该通过

 if (head == NULL)

我认为错误在 if(head == tail) 行,如果将其更改为 if(head == NULL) 它应该打印 10 20 30。但是,如果您想知道为什么 if(head == tail) 导致这个问题是因为对于每个 addNode 操作,head 和 tail 都是相等的,最后 head 也指向 30!

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM