gpt4 book ai didi

c++ - 如何将深拷贝构造函数实现到链表中?

转载 作者:行者123 更新时间:2023-11-28 04:10:09 29 4
gpt4 key购买 nike

对于我目前正在处理的这个问题,我正在尝试在此链表中创建一个方法来执行从一项到另一项的深层复制。现在该方法的内部是空的,因为我无法为我的生活工作。有没有什么办法可以帮助我在下面注释的代码区域中实现这个深拷贝构造函数?谢谢。

#include <string>
#include <iostream>
#include <cstddef>

using std::string;

class Item {

public:

string s;

Item(const char *a_s = "") {
s = a_s;
}

Item(string a_s) {
s = a_s;
}
};


class List {

private:

class ListNode {

public:
Item item;
ListNode * next;
ListNode(Item i) {
item = i;
next = nullptr;
}
};

ListNode * head;
ListNode * tail;

public:

class iterator {

ListNode *node;

public:
iterator(ListNode *n = nullptr) {
node = n;
}

Item& getItem() { return node->item; } //Not sure how this works
void next() { node = node->next; }
bool end() { return node==nullptr; }

};



public:

List() {
head = nullptr;
tail = nullptr; //Sets the head and tail
}

List(const List & copy) { //Trying to create a copy constructor right here.

}

bool empty() { //Tells you if the list is empty
return head==nullptr;
}

void append(Item a) {

ListNode *node = new ListNode(a);
if ( head == nullptr ) {
head = node;
tail = node;
} else {
tail->next = node;
tail = node;
}
}

bool remove (Item &copy);

void traverse() {
ListNode *tmp = head;
while(tmp != nullptr) {
tmp = tmp->next;
}
}

iterator begin() const {
return iterator(head);
}

};

bool List::remove(Item &copy)
{
if (!empty()) {
copy = head->item;
ListNode *tmp = head->next;
delete head;
head = tmp;
if (head==nullptr)
tail = nullptr;
return true;
}
return false;
}


int main() {
List l;
l.append("eggs");

List l2 = l;

std::cout << "done.\n";

return 0;
}

最佳答案

假设 append() 正常工作,您可以在循环中为 copy 中的每个项目重复调用它。

鉴于您如何使用 tail 指针实现链表,这种方法使其成为理想的解决方案。您编写了 append 函数,所以这只是以战略方式使用它的问题。

但是请注意,如果您实现的链表没有尾指针(您必须遍历到列表的末尾以 append),这种方法仍然有效,但会效率极低且不令人满意。

这是一个例子(未经测试):

List(const List & copy) : head(nullptr), tail(nullptr) 
{
ListNode *copyNode = copy.head;
while (copyNode)
{
append(copyNode->item);
copyNode = copyNode->next;
}
}

请注意,这并未针对边界条件进行测试,因此您可能需要在执行循环之前检查 copy 是否为空。

Here is an example that works for a simple case

关于c++ - 如何将深拷贝构造函数实现到链表中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58002259/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com