首页 > 解决方案 > 单链表,实践实现

问题描述

我正在准备一些面试,我试图快速编写一个基本的单链表。代码编译得很好,但似乎没有打印出来,我不知道为什么。

这就是我所做的:

#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 但它不打印任何内容。知道为什么吗?

标签: c++linked-listc++14

解决方案


你没有更新你的headin push_back()。代替

if (!head) { newNode = std::move(head); ... }

你应该做

if (!head) {head = std::move(newNode); ... }

推荐阅读