C++ 如何在这个交换函数(单链表)中找到bug?

C++ 如何在这个交换函数(单链表)中找到bug?,c++,singly-linked-list,C++,Singly Linked List,如果其中一个是头,我无法交换链表中的值。我在a中插入了三个值(4、5、7),删除了2,交换了5、4,但当其中一个值是头时,代码不会交换,当其中一个值是头时,它不会交换并显示输出。相同的代码适用于非头节点 struct node { int x; node* next; }; void swapper(node **headref, int a, int b) { node *temp1 = *headref, *temp2 = *headref, *prev2 = NULL, *pr

如果其中一个是头,我无法交换链表中的值。我在a中插入了三个值(4、5、7),删除了2,交换了5、4,但当其中一个值是头时,代码不会交换,当其中一个值是头时,它不会交换并显示输出。相同的代码适用于非头节点

struct node
{
int x;

node* next;
};

void swapper(node **headref, int a, int b)
{
    node *temp1 = *headref, *temp2 = *headref, *prev2 = NULL, *prev1 = NULL;

    while(temp1 != NULL && temp1->x != a)
    {
        prev1 = temp1;
        temp1 = temp1->next;
    }

    while(temp2 != NULL && temp2->x != b)
    {
        prev2 = temp2;
        temp2 = temp2->next;
    }

    if(temp1 == *headref)
    {
        swap(temp1->next, temp2->next);
        prev2->next = *headref;
        *headref = temp2;
    }

    if(temp2 == *headref)
    {
        swap(temp1->next, temp2->next);
        prev1->next = *headref;
        *headref = temp1;
    }

    if(temp1 != NULL && temp2 != NULL)
    {
        swap(prev1->next, prev2->next);
        swap(temp1->next, temp2->next);
    }
}
输出:
4 1 2 3
4 1 2 5 3 
4 1 2 5 3 7 
4 1 5 3 7  

它应该交换5和4并显示51437,但这没有发生。我无法在代码中找到bug。

问题是您没有正确地考虑不同的情况。如果你需要交换,那么你应该只做一次交换,所以你应该有一个If。。。否则如果。。。else语句来处理不同的情况

在您的示例中,具体出现的错误是
temp1===*headref
然后发生交换,但是在交换
temp2==*headref
之后,程序尝试第二次交换

如果您试图用列表中未列出的内容交换头部,也会出现错误,在这种情况下,(例如)
temp1==*headref
temp2==NULL
,这将是一个问题

最后一个bug是将头部与自身交换。这也会崩溃,因为在这种情况下
prev2==NULL

这是一个有效的版本。正如你所看到的,它与你的非常相似,我刚刚仔细考虑了不同的交换方式

void swapper(node **headref, int a, int b)
{
    node *temp1 = *headref, *temp2 = *headref, *prev2 = NULL, *prev1 = NULL;

    while (temp1 != NULL && temp1->x != a)
    {
        prev1 = temp1;
        temp1 = temp1->next;
    }

    while (temp2 != NULL && temp2->x != b)
    {
        prev2 = temp2;
        temp2 = temp2->next;
    }

    if (temp1 == NULL || temp2 == NULL || temp1 == temp2)
    {
        // nothing to do
    }
    else if (temp1 == *headref)
    {
        swap(temp1->next, temp2->next);
        prev2->next = *headref;
        *headref = temp2;
    }
    else if (temp2 == *headref)
    {
        swap(temp1->next, temp2->next);
        prev1->next = *headref;
        *headref = temp1;
    }
    else
    {
        swap(prev1->next, prev2->next);
        swap(temp1->next, temp2->next);
    }
}

说到这里,我对您编写的代码的质量印象深刻。样式很好,很容易理解,很接近正确,一旦发现错误就很容易修复。

仍然缺少
节点
的定义。请阅读有关如何提供服务的信息。阅读也可以帮助你。你真的需要交换节点本身吗?为什么不直接交换节点内的值呢?对不起,我忘了提问题是交换节点本身而不是值()非常感谢!尽管我的问题被否决了,但还是感谢你的帮助:)