我正在尝试从小到大对链表中的数字进行排序。
但是它不起作用!
调试器说,当我将第二个数字放到
清单(主要)但我不知道为什么。
有什么帮助吗?
#include<stdio.h>
#include<stdlib.h>
typedef struct list list;
struct list{
int a;
list *nxt;
};
void sort(list *l){
int temp,tp;
list *AIDE,*k;
k=AIDE=(list*)malloc(sizeof(list));
while (l->nxt!= NULL)
{
while (l->nxt->a < l->a)
{
temp=l->a;
l=l->nxt;
l->nxt->a=temp;
l=l->nxt;
while (l->a < AIDE->nxt->a )
{
tp=AIDE->a;
AIDE->a=l->a;
AIDE->nxt->a=tp;
AIDE=AIDE->nxt;
}
}
l=l->nxt;
}
while (k->nxt!= NULL)
{
l->a=k->a;
l=l->nxt;
k=k->nxt;
}
l->nxt=NULL;
}
int main() {
list *t,*s;
int n,i,c=0;
printf("\n how many number you need to enter? ");
scanf("%d",&n);
s=t=(list*)malloc(sizeof(list)*n);
while (c!=n)
{
printf("\n Donner le nb %d :",c+1);
scanf("%d",&t->a);
t=t->nxt;
c++;
}
t->nxt=NULL;
sort(s);
while (t->nxt!=NULL)
{
printf("%d",t->a);
}
return 0;
}
最佳答案
在出现问题的循环中,您认为t=t->nxt
表达式会做什么?
当您进入循环时,t
指向已分配但未初始化的内存,因此取消引用例如t->nxt
将导致undefined behavior。
一个简单的解决方案是做
t->nxt = t++ + 1;
关于c - 链接列表从最小到最大排序,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/29579984/