#include<stdio.h>
#include<stdlib.h>
struct arry{
long num;
struct arry *next;
};
main()
{
char end_input,sort_type;
long num,crls=0;/*crls用于判断输出是否需要换行*/
unsigned long p_count=0;/*指针编号计数器*/
struct arry *head,*cur,*temp,*last;/*t1t2用于输入,f1f2用于查找和排序*/
head=(struct arry*)malloc(sizeof(struct arry));
head->next=NULL;
last=cur=head;
puts("Please choose a type of sort:U(High-->Low)/D(Low-->High)");
printf(">>");/*仿Unix输入提示符^_^*/
scanf("%c",&sort_type);
getchar();/*吸收多余的回车*/
while (sort_type!='u'&&sort_type!='U'&&sort_type!='d'&&sort_type!='D')
{
puts("Illigal input./nPlease choose a type of sort:U(High-->Low)/D(Low-->High)");
printf(">>");
scanf("%c",&sort_type);
getchar();/*吸收多余的回车*/
}/*排序类型标识符,U/u降序,D/d升序*/
do
{
temp=(struct arry*)malloc(sizeof(struct arry));
temp->next=NULL;
cur->next=temp;
cur=temp;
printf(">>");
scanf("%ld",&cur->num);
getchar();
switch (sort_type)
{
case 'u':
case 'U':
for (temp=head;temp->next!=NULL;temp=temp->next)
{
if (cur->num>temp->next->num)/*当前数字比表中的大的时候*/
{
cur->next=temp->next;
temp->next=cur;
last->next=NULL;
cur=last;/*原来的代码有一段是cur->next->next=NULL
其实这样做,会把后面的链表给打断,最大的错误*/
break;
}
if (temp->next->next==NULL)last=cur;
}
break;
case 'd':
case 'D':
for (temp=head;temp->next!=NULL;temp=temp->next)
{
if (cur->num<temp->next->num)
{
cur->next=temp->next;
temp->next=cur;
last->next=NULL;
cur=last;
/*原来的错误同上*/
break;
}
if (temp->next->next==NULL)last=cur;/*
之前代码说明cur已经接在链尾,这里是更新尾指针*/
}
break;
}/*switch语句结束*/
printf("End input?(Y for exit,other for continue)");
end_input=getchar();
getchar();
}while (end_input!='y'&&end_input!='Y');/*end_input为结束输入标识符*/
#if 0
temp=(struct arry*)malloc(sizeof(struct arry));
cur->next=temp;/*建立前件与新指针的连接*/
temp->next=NULL;
cur=temp;/*创立并且指向当前新创立的指针*/
#endif
printf("The sorted numbers:");
for (temp=head;temp->next!=NULL;temp=temp->next)
{
if (crls%5==0)putchar('/n');
printf("%10ld",temp->next->num);
crls++;
}
putchar('/n');
/*接下来释放开辟的地址*/
cur=head;
for (temp=head;cur->next!=NULL;temp=cur)
{
printf("Freed address:%X/n",temp);
cur=temp->next;
free(temp);
}
free(cur);
printf("Freed address:%X/n/n",temp);
puts("All allocated memories have been freed.");
system("pause");
}
插入排序(单链表)
最新推荐文章于 2024-04-13 11:38:34 发布
265

被折叠的 条评论
为什么被折叠?



