c++ - 单链表,实践实现
问题描述
我正在准备一些面试,我试图快速编写一个基本的单链表。代码编译得很好,但似乎没有打印出来,我不知道为什么。
这就是我所做的:
#include <iostream>
#include <memory>
#include <utility>
struct Node {
int data;
std::unique_ptr<Node> next = nullptr;
Node(const int& x, std::unique_ptr<Node>&& p = nullptr)
: data(x)
, next(std::move(p)) {}
};
std::unique_ptr<Node> head;
Node* tail;
void print() {
auto temp = head.get();
while (temp) {
std::cout << temp->data << " ";
temp = temp->next.get();
}
std::cout << "\t";
}
void push_back(const int& theData) {
std::unique_ptr<Node> newNode = std::make_unique<Node>(theData);
if (!head) {
newNode = std::move(head);
tail = head.get();
}
else {
tail->next = std::move(newNode);
tail = tail->next.get();
}
}
int main() {
head = nullptr;
tail = nullptr;
push_back(2);
push_back(4);
push_back(6);
print();
std::cin.get();
}
这应该打印 2 4 6 但它不打印任何内容。知道为什么吗?
解决方案
你没有更新你的head
in push_back()
。代替
if (!head) { newNode = std::move(head); ... }
你应该做
if (!head) {head = std::move(newNode); ... }
推荐阅读
- bootstrap-4 - Ng-bootstrap Carousel 缺少滑动效果
- python - 函数没有返回正确的值(Python)
- python-3.x - tf.keras plot_model: add_node() 收到一个非节点类对象
- c# - XAMARIN ANDROID 应用程序得到 System.ServiceModel.FaultException
- android - 获取数据并将其显示在 list.Builder 上时出现 Android HWUI 错误
- crystal-reports - Crystal Reports PO 添加第二页条款和条件
- rust - 为 WSL 安装 Rust 时,线程“主”在“断言失败:`(左 == 右)` 左:`22`,右:`4`'时惊慌失措
- python - 在 pandas read_csv 中加载数据时的操作顺序
- javascript - 如何让 setState 在 setInterval 中工作?(目前正在工作)
- javascript - 有条件地显示 html 并仅在存在值时显示