【发布时间】:2018-01-13 09:09:49
【问题描述】:
我在交换单链表中的相邻节点时遇到了一些问题。这是我的交换功能:
void swap(std::shared_ptr<ListItem> root, int indexA, int indexB)
{
if (indexA == 0)
{
std::shared_ptr<ListItem> A = root;
std::shared_ptr<ListItem> B = A->next;
A->next = B->next;
B->next = A;
root = B;
}
else if (indexB == 0)
{
std::shared_ptr<ListItem> B = root;
std::shared_ptr<ListItem> A = B->next;
B->next = A->next;
A->next = B;
root = A;
}
else
{
std::shared_ptr<ListItem> preA = GetNode(root, indexA - 1);
std::shared_ptr<ListItem> preB = GetNode(root, indexB - 1);
std::shared_ptr<ListItem> A = preA->next;
std::shared_ptr<ListItem> B = preB->next;
std::shared_ptr<ListItem> temp = B->next;
preA->next = B;
A->next = temp;
B->next = A;
}
}
现在您可以看到此代码仅处理相邻节点。那是因为我只在我的排序函数中使用它:
void LinkedList::sort() {
for (int i = 0; i <= this->getSize(); i++)
{
int j = i;
while (j > 0 && getItem(j) < getItem(j - 1))
{
swap(root, (j - 1), j);
j = j - 1;
}
}
}
所以每次运行swap函数,送进来的节点都是相邻的。我的问题是我现在交换的方式我丢失了节点,它们之间的链接在某个地方断开了,但我真的不明白为什么或在哪里。我的猜测是我需要使用一个临时节点,但是因为我不明白链接断开的原因或位置,我也不知道我需要在哪里使用临时节点。
此外,preB 节点目前从未使用过,这是许多修复失败尝试的残余。任何提示将不胜感激!
【问题讨论】:
-
root = A;更改本地副本。 -
Aaah....所以我必须返回更改后的根目录...或者还有其他方法可以让交换函数保持无效?
-
使用...调用
-
已修复,但我原来的问题仍然存在。
-
使用调试器。
标签: c++ linked-list