gpt4 book ai didi

c++ - 复制函数链表c++

转载 作者:行者123 更新时间:2023-11-28 00:21:09 25 4
gpt4 key购买 nike

我正在尝试编写一个函数来将一个链表的内容复制到一个新的链表中(不引用第一个 LL)。到目前为止,我得到了这个:

void List::copy(const List& otherList)
{
assert(head == nullptr);
if (otherList.head != nullptr)
{
head = new Node;
assert(head != nullptr);
head->item = otherList.head->item;
Node* ptr1 = head;
for (Node* ptr2 = otherList.head->next; ptr2 != nullptr; ptr2=ptr2->next)
{
ptr1->next = new Node;
assert(ptr1->next != nullptr);
(ptr1->next)->item = ptr2->item;
(ptr1->next)->next = ptr2-> next;
}
}
}

然而,当我在一个小型链表上运行代码时,它只是复制了第一个和最后一个节点——出于某种原因,它遗漏了中间部分。我花了一段时间研究其他人的解决方案并试图找出我的问题所在,但是我遇到了困难!

有人能指出我哪里错了吗?

亲切的问候

克雷格

最佳答案

您没有迭代新列表。

void List::copy(const List& otherList)
{
assert(head == nullptr);
if (otherList.head != nullptr)
{
head = new Node;
assert(head != nullptr);
head->item = otherList.head->item;
Node* ptr1 = head;
for (Node* ptr2 = otherList.head->next; ptr2 != nullptr; ptr2=ptr2->next)
{
ptr1->next = new Node;
assert(ptr1->next != nullptr);
(ptr1->next)->item = ptr2->item;
ptr1 = ptr1->next;
}
ptr1->next = 0;
}
}

关于c++ - 复制函数链表c++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27405187/

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