如何在这个交换函数(一个单独的链表)中找到错误
How to find the bug in this swap function (a 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, *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 == *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);
}
}
说了这么多,我真的对你写的代码的质量印象深刻。这种风格很好,很容易遵循,它几乎是正确的,一旦发现错误就很容易修复。
相关文章:
- 错误:需要类名(链表c++)
- 对单向链表进行排序时出现运行时错误
- 在链表中的第 n 位插入显示分割错误
- 链表错误的中间
- 为什么我在空指针错误(链表)中获取成员访问权限
- 查找显示链表时出现的错误
- 我想在 c++ 中对单向链表进行冒泡排序,但我一直面临左值错误,无法解决它
- 在 c++ 中实现链表时出现分段错误
- 双链表的擦除值函数,未知错误
- 删除链表中的节点 - 分段错误
- 分段错误通用双链表
- C++中链表的错误"Abort signal from abort(3) (sigabrt) "
- 奇怪的C++链表错误
- 在C++中使用链表的堆栈实现中,访问结构体headNode成员count和top会导致运行时错误
- 为什么我的C++代码在以下打印链表的代码片段中显示分段错误?
- C++:按数字排序链表错误
- 为什么我在尝试添加两个链表时出现此错误?
- C++ largest_free节点函数段错误链表
- 析构函数分段错误链表
- c++分割错误链表元素添加