簡體   English   中英

雙向鏈表的自定義實現不起作用(教育)

[英]Custom implementation of doubly linked list not working (educational)

我實現了我自己的簡單版本的雙向鏈表。 不幸的是,它似乎有一個錯誤。 列表的頭部似乎移動到新的Node ,每次我用push_back添加一個。 因此, print將無限期地打印最后一個值。

鏈接列表:

struct doubly_linked_list
{
    Node *head = nullptr;
    Node *tail = nullptr;
    void push_back(Node n)
    {
        if (this->head == nullptr)
        {
            this->head = &n;
            this->tail = nullptr;
        }
        n.prev = this->tail;
        if (this->tail)
        {
            n.prev->next = &n;
        }
        this->tail = &n;
    }
    void print()
    {
        Node *tmp = this->head;
        while (tmp != nullptr)
        {
            std::cout << tmp->data << ", ";
            tmp = tmp->next;
        }
    }
};

其中Node實現為

struct Node
{
    int data;
    Node *next = nullptr;
    Node *prev = nullptr;
    Node(int data)
    {
        this->data = data;
    }
    Node()
    {
        this->data = -1;
    }
};

主要的

int main()
{
    doubly_linked_list dl;
    dl.push_back(Node{3});
    dl.push_back(Node{2});
    dl.push_back(Node{1});
    dl.push_back(Node{0});
    dl.push_back(Node{5});
    dl.print(); // print 5 forever
}

免責聲明:請注意,這篇文章的主題是教育性的。 我知道 C++ 標准中的列表。

這是一個帶有原始指針的工作示例,根據您在做什么,您可能希望將其更改為智能指針。

#include <iostream>

struct Node
{
    int data;
    Node *next = nullptr;
    Node *prev = nullptr;
    Node(int data)
    {
        this->data = data;
    }
    Node()
    {
        this->data = -1;
    }
};

struct doubly_linked_list
{
    Node *head = nullptr;
    Node *tail = nullptr;
    void push_back(Node* n)
    {
        if (this->head == nullptr)
        {
            this->head = n;
            this->tail = nullptr;
        }
        n->prev = this->tail;
        if (this->tail)
        {
            n->prev->next = n;
        }
        this->tail = n;
    }
    void print()
    {
        Node *tmp = this->head;
        while (tmp != nullptr)
        {
            std::cout << tmp->data << ", ";
            tmp = tmp->next;
        }
     }
};

int main()
{
    doubly_linked_list dl;
    dl.push_back(new Node{3});
    dl.push_back(new Node{2});
    dl.push_back(new Node{1});
    dl.push_back(new Node{0});
    dl.push_back(new Node{5});
    dl.print(); // print 5 forever
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM