【问题标题】:C++ Swapping adjacent nodes in a linked listC ++交换链表中的相邻节点
【发布时间】: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


【解决方案1】:

所以事实证明我的问题是我以前从未考虑过的。就是排序函数中的这一行:

for (int i = 0; i <= this->getSize(); i++)

这总是会让它走得太远,而且我在 getItem() 中添加了一种故障保护,这使得它很难确定。基本上在 getItem() 中,我说如果我要查找的节点是 nullptr,则返回 0。这真的很愚蠢,因为它看起来好像问题出在 swap() 而不是 sort()。

所以我把那一行改成:

for (int i = 0; i < this->getSize(); i++)

现在它可以工作了。真是愚蠢的错误,我为浪费人们的时间而道歉。也非常感谢 @manni66 帮助我解决这个问题!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多