Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

wyh hw02 #72

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
32 changes: 19 additions & 13 deletions main.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -5,29 +5,27 @@
struct Node {
// 这两个指针会造成什么问题?请修复
std::shared_ptr<Node> next;
std::shared_ptr<Node> prev;
std::weak_ptr<Node> prev;
// 如果能改成 unique_ptr 就更好了!

int value;

// 这个构造函数有什么可以改进的?
Node(int val) {
value = val;
}
// 这个构造函数有什么可以改进的?
explicit Node(int val=0): value(val) { }

void insert(int val) {
auto node = std::make_shared<Node>(val);
node->next = next;
node->prev = prev;
if (prev)
prev->next = node;
if (!prev.expired())
prev.lock()->next = node;
if (next)
next->prev = node;
}

void erase() {
if (prev)
prev->next = next;
if (!prev.expired())
prev.lock()->next = next;
if (next)
next->prev = prev;
}
Expand All @@ -43,12 +41,20 @@ struct List {
List() = default;

List(List const &other) {
printf("List 被拷贝!\n");
head = other.head; // 这是浅拷贝!
printf("List be copied!\n");
// head = other.head; // 这是浅拷贝!
// 请实现拷贝构造函数为 **深拷贝**
head = std::make_shared<Node>(other.head->value);
auto now = head, othead = other.head; //浅拷贝
while(othead->next){
now->next = std::make_shared<Node>(othead->next->value);
now->next->prev = now;
now = now->next, othead = othead->next;
}
}

List &operator=(List const &) = delete; // 为什么删除拷贝赋值函数也不出错?
List &operator=(List const &) = delete;
// 为什么删除拷贝赋值函数也不出错? 因为编译器默认使用析构函数+拷贝构造来代替拷贝赋值函数

List(List &&) = default;
List &operator=(List &&) = default;
Expand Down Expand Up @@ -80,7 +86,7 @@ struct List {
}
};

void print(List lst) { // 有什么值得改进的?
void print(const List& lst) { // 有什么值得改进的?传参const List&,减少拷贝并提高运行速度,减少运行时内存占用
printf("[");
for (auto curr = lst.front(); curr; curr = curr->next.get()) {
printf(" %d", curr->value);
Expand Down