C++ 单链表,实践实施
我正在准备一些面试,我试着快速地写一个基本的单链表。代码编译得很好,但似乎没有打印出来,我不知道为什么 这就是我所做的:C++ 单链表,实践实施,c++,linked-list,c++14,C++,Linked List,C++14,我正在准备一些面试,我试着快速地写一个基本的单链表。代码编译得很好,但似乎没有打印出来,我不知道为什么 这就是我所做的: #include <iostream> #include <memory> #include <utility> struct Node { int data; std::unique_ptr<Node> next = nullptr; Node(const int& x, std::uni
#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();
}
#包括
#包括
#包括
结构节点{
int数据;
std::unique_ptr next=nullptr;
节点(const int&x,std::unique_ptr&&p=nullptr)
:数据(x)
,next(std::move(p)){}
};
std::唯一的ptr头;
节点*尾部;
作废打印(){
自动温度=head.get();
while(临时){
std::cout data next.get();
}
std::cout next=std::move(newNode);
tail=tail->next.get();
}
}
int main(){
水头=零PTR;
tail=nullptr;
推回(2);
推回(4);
推回(6);
打印();
std::cin.get();
}
这应该打印2 4 6,但它不打印任何内容。知道为什么吗?在
push_back()
中,你没有抬起你的头。而不是
if (!head) { newNode = std::move(head); ... }
你应该做什么
if (!head) {head = std::move(newNode); ... }
使用调试器逐行检查代码时,您观察到了什么?std::move
ingint
或const int&
与传递一个简单的、复制的int
@πάντα完全相同ῥεῖ 我还没有学会如何很好地使用断点。@snorlaxxx知道如何使用调试器对每个程序员来说都是一项非常重要的技能。如果他们要问这个问题,你打算在面试中告诉他们什么?