diff --git a/main.cpp b/main.cpp index dc25c6b..78abbfa 100644 --- a/main.cpp +++ b/main.cpp @@ -1,35 +1,38 @@ /* 基于智能指针实现双向链表 */ #include #include +#include struct Node { // 这两个指针会造成什么问题?请修复 - std::shared_ptr next; - std::shared_ptr prev; + std::unique_ptr next; + Node *prev{}; // 如果能改成 unique_ptr 就更好了! int value; // 这个构造函数有什么可以改进的? - Node(int val) { - value = val; + explicit Node(int val):value(val) { } void insert(int val) { - auto node = std::make_shared(val); - node->next = next; + auto node = std::make_unique(val); node->prev = prev; - if (prev) - prev->next = node; - if (next) - next->prev = node; + if (next) { + next->prev = node.get(); + } + node->next = std::move(next); + if (prev) { + prev->next = std::move(node); + } } void erase() { - if (prev) - prev->next = next; if (next) next->prev = prev; + if (prev) { + prev->next=std::move(next); + } } ~Node() { @@ -38,14 +41,28 @@ struct Node { }; struct List { - std::shared_ptr head; + std::unique_ptr head; List() = default; List(List const &other) { printf("List 被拷贝!\n"); - head = other.head; // 这是浅拷贝! +// head = other.head; // 这是浅拷贝! // 请实现拷贝构造函数为 **深拷贝** + auto node = std::make_unique(other.head->value); + auto node_ptr=node.get(); + head=std::move(node); + + auto curr = other.head->next.get(); + while(curr){ + auto cur_node=std::make_unique(curr->value); + auto cur_node_ptr=cur_node.get(); + cur_node->prev=node_ptr; + node_ptr->next=std::move(cur_node); + node_ptr=cur_node_ptr; + + curr = curr->next.get(); + } } List &operator=(List const &) = delete; // 为什么删除拷贝赋值函数也不出错? @@ -59,16 +76,16 @@ struct List { int pop_front() { int ret = head->value; - head = head->next; + head.reset(head->next.get()); return ret; } void push_front(int value) { - auto node = std::make_shared(value); - node->next = head; - if (head) - head->prev = node; - head = node; + auto node = std::make_unique(value); + node->next = std::move(head); + if (node->next) + node->next->prev = node.get(); + head=std::move(node); } Node *at(size_t index) const { @@ -80,7 +97,7 @@ struct List { } }; -void print(List lst) { // 有什么值得改进的? +void print(const List &lst) { // 有什么值得改进的? printf("["); for (auto curr = lst.front(); curr; curr = curr->next.get()) { printf(" %d", curr->value); diff --git a/run.sh b/run.sh old mode 100755 new mode 100644 index 99e6ef6..1183e5e --- a/run.sh +++ b/run.sh @@ -1,5 +1,5 @@ #!/bin/sh set -e -cmake -B build +cmake -B build -DCMAKE_BUILD_TYPE=False cmake --build build build/main