双链表的自定义实现不起作用(教育)

Custom implementation of doubly linked list not working (educational)

本文关键字:教育 不起作用 实现 链表 自定义      更新时间:2023-10-16

我实现了自己的双链表的简单版本。不幸的是,它似乎有一个错误。列表的头部似乎移动到新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;
}
}
};

其中节点实现为

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
}