为什么这个交换不必更改以前的链接但仍然可以运行
下面的代码是从 geekforgeeks 复制的。我对交换感到好奇 它没有改变前一个节点的下一个节点。 为什么排序后还能打印出正确答案呢? 如果它改变了前一个节点的下一个链接,那么在哪里?
感谢您的回答。
struct Node* swap(struct Node* ptr1, struct Node* ptr2)
{
struct Node* tmp = ptr2->next;
ptr2->next = ptr1;
ptr1->next = tmp;
return ptr2;
}
int bubbleSort(struct Node** head, int count)
{
struct Node** h;
int i, j, swapped;
for (i = 0; i <= count; i++) {
h = head;
swapped = 0;
for (j = 0; j < count - i - 1; j++) {
struct Node* p1 = *h;
struct Node* p2 = p1->next;
if (p1->data > p2->data) {
/* update the link after swapping */
*h = swap(p1, p2);
swapped = 1;
}
h = &(*h)->next;
}
/* break if the loop ended without any swap */
if (swapped == 0)
break;
}
}
Below code is copy from geekforgeeks. I'm curious about the swap
It didn't change the previous node's next.
Why can it still print the right answer after sort?
If it has change previous node's next link, then where?
Thanks for answering.
struct Node* swap(struct Node* ptr1, struct Node* ptr2)
{
struct Node* tmp = ptr2->next;
ptr2->next = ptr1;
ptr1->next = tmp;
return ptr2;
}
int bubbleSort(struct Node** head, int count)
{
struct Node** h;
int i, j, swapped;
for (i = 0; i <= count; i++) {
h = head;
swapped = 0;
for (j = 0; j < count - i - 1; j++) {
struct Node* p1 = *h;
struct Node* p2 = p1->next;
if (p1->data > p2->data) {
/* update the link after swapping */
*h = swap(p1, p2);
swapped = 1;
}
h = &(*h)->next;
}
/* break if the loop ended without any swap */
if (swapped == 0)
break;
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
它因赋值而改变
双指针
h
指向前一个节点的数据成员next
或通过指向它的指针间接通过引用传递给函数的指针头执行此语句后,
前一个节点的数据成员
next
获取指针p2
的值。指针p2
指向的节点的数据成员next
获取指针p1
的值和数据成员next<指针
p1
指向的节点的/code>获取指针p2
指向的节点的数据成员next
的初始存储值代码>.It changes due to the assignment
The double pointer
h
points to the data membernext
of the previous node or to the pointer head passed to the function by reference indirectly through pointer to it die to this statementAfter this assignment
the data member
next
of the previous node gets the value of the pointerp2
. The data membernext
of the node pointed to by the pointerp2
gets the value of the pointerp1
and the data membernext
of the node pointed to by the pointerp1
gets the initially stored value of the data membernext
of the node pointed to by the pointerp2
.