[英]Problems ordering a linked list in C
I got issues trying to order a linked list from its min to its max, the code is: 我在尝试从最小到最大排序链表时遇到问题,代码是:
struct nodo *orderList (struct nodo *p) {
struct nodo *head=p;
struct nodo *min=p;
int *tmp=NULL;
while (min != NULL) {
p = min;
// p = p->succ (not necessary i think)
while (p != NULL) {
if (p->info < min->info) {
tmp = &min->info;
min->info = p->info;
p->info = *tmp;
}
p=p->succ;
}
min=min->succ;
}
return head;
}
The output i get (i use a tested function to create a list with n nodes from input) : 我得到的输出(我使用一个经过测试的函数从输入创建具有n个节点的列表):
Number of elements: 4
insert 4 positive numbers:
4
3
2
1
1 -> 1 -> 1 -> 1 ->
By using a int *
, when you swap the info field, you refer to the modified field. 通过使用
int *
,当您交换信息字段时,可以引用修改后的字段。
You should declare tmp
as: 您应该将
tmp
声明为:
int tmp;
and adjust your swap code accordingly. 并相应地调整交换代码。
In this way you would copy the value of min->info
before changing it. 这样,您可以在更改之前复制
min->info
的值 。
This code does not swap the data 此代码不交换数据
tmp = &min->info;
min->info = p->info;
p->info = *tmp;
The third line simply moves the data back to where it was, since min->info
now contains p->info
. 第三行只是将数据移回原来的位置,因为
min->info
现在包含p->info
。
You need to swap like this 您需要像这样交换
int tmp = min->info;
min->info = p->info;
p->info = tmp;
assuming the data type is int
as you didn't post the struct
. 假设数据类型为
int
因为您没有发布struct
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.