如何在这个交换函数(一个单独的链表)中找到错误

How to find the bug in this swap function (a singly linked list)?

本文关键字:错误 链表 单独 交换 函数 一个      更新时间:2023-10-16

如果链表中有一个值是头,我就无法交换它们。我在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);
}
}
Output:
4 1 2 3
4 1 2 5 3 
4 1 2 5 3 7 
4 1 5 3 7  

它应该交换5和4并显示5 1 4 3 7,但这并没有发生。我在代码中找不到错误。

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

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

如果你试图用列表中没有的东西交换头部,你也会遇到一个错误,在这种情况下,你会有(例如)temp1 == *headreftemp2 == 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);
}
}

说了这么多,我真的对你写的代码的质量印象深刻。这种风格很好,很容易遵循,它几乎是正确的,一旦发现错误就很容易修复。