簡體   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