链接列表泡泡排序的麻烦
我是一个初学者,学习使泡沫排序与链接列表一起工作。我看到了一个geeksforgeeks页面,谈论了这一点(),并适应了我的情况。我已经获得了适当工作的代码,但是我很难了解逻辑在此分类中的工作原理。为了理解“头”作为基点,它总是指示第一个节点。但是据我所知,头指针应始终与节点一起移动(如果节点A和B交换,并且头指向A,那么即使在交换后,头也会继续指向A),这似乎与第一个陈述相矛盾。
这是我的代码:
typedef struct Node{
int Nid;
char Nname[9];
int Ngrades;
struct Node *next;
}NODE;
int bubbleSortID(NODE** head, int count){
NODE** h;
NODE* temp;
for (int i = 0; i <= count; i++) {
h = head;
for (int j = 0; j < count-1; j++) {
NODE* p1 = *h;
NODE* p2 = p1->next;
if (p1->Nid > p2->Nid) {
temp = p2->next;
p2->next = p1;
p1->next = temp;
*h = p2;
}
h = &(*h) -> next;
}
}
}
void getID(NODE *head){ //used to print result
while (head != NULL){
printf("%d %s %d \n", head->Nid, head->Nname, head->Ngrades);
head = head->next;
}
}
given input:
10355112 jack 80
10311103 tom 85
10355107 zenry 70
10355014 tim 95
10355123 mary 85
11355123 helloo 1000
expected output:
10311103 tom 85
10355014 tim 95
10355107 zenry 70
10355112 jack 80
10355123 mary 85
11355123 helloo 1000
有人可以帮助我了解此代码中发生的情况吗?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
是的,但是不要将此
head
变量与另一个变量,h
变量混淆,该变量并非始终在第一个节点处(间接)点。另请注意,当
h =&amp;(*h) - &gt; Next;
被执行,h
和head
不再是相同的指针,*H
不再是第一个节点列表。然后,H
已成为下一个
指针的地址,该节点是在下一个迭代中由p1
引用的节点之前的。这就是为什么
> *h = p2
已执行,因此*h
可以保证指向具有较小值的节点,并且不遵守交换之前的节点。这成为 block 块之后的不变性:是否执行该块,*h
是指比较中使用的另一个节点背后的节点,他们处于正确的顺序。Yes, but don't confuse this
head
variable with another variable,h
, which is not intended to always (indirectly) point at the first node.Also note that when
h = &(*h) -> next;
is executed,h
andhead
are no longer the same pointer, and*h
is no longer the first node of the list.h
has then become the address of thenext
pointer of the node that precedes the node that will be referenced byp1
in the next iteration.True, and that is why
*h = p2
is executed, so that*h
is guaranteed to point to the node that has the lesser value, and does not stick to what it was before the swap. This becomes the invariant after theif
block: whether or not that block was executed,*h
refers to the node behind the other node that was used in the comparison, and they are in their right order.