类型:转载 责任编辑:asp 日期:2007/03/01
我的这个程序是输入数字,int形的,然后按i或者i(也就是insert的简写)插入新的数字到链表中去,然后按l或者l(也就是listall的简写)把刚才输入的数据输出到屏幕上。现在想加入一个新函数,功能是把刚才输入的数据排序,这函数名字叫sorting。我的原代码在下面,(注:除了main函数外有三个函数,insert是插入数据用的,listall是列出数据,就剩下sorting这个函数了,我现在一点思路没有,请大家在我的注解那看看能添社什么代码,感激不尽,我不富裕,100分相送):
#include<stdlib.h>
#include<stdio.h>
void insert(void);
void listall(void);
void sorting(void);
struct datatype
{int num;
struct datatype *next;
};
struct datatype *head,*this,*new;
void main(void)
{char ch;
int flag=1;
head=0;
while(flag)
{printf("type i or i to enter new number,\n");
printf("type l or l to list all numbers,\n");
printf("type all others key to exit:");
ch=getchar();getchar();
switch(ch)
{case i:
case i:insert();break;
case l:
case l:sorting();listall();break;
default:flag=0;
}
}
}
void insert(void)
{char numstr[20];
new=(struct datatype *)malloc(sizeof(struct datatype));
if(head==0)
head=new;
else
{this=head;
while(this->next!=0)
this=this->next;
this->next=new;
}
this=new;
printf("enter age:");
gets(numstr);
this->num=atoi(numstr);
this->next=0;
}
void sorting(void)
{
/*排序的函数*/
}
void listall(void)
{int i=0;
if(head==0)
{printf("\nempty list.\n");return;}
this=head;
printf("\nthe new numbers list:\n");
do{
printf("the [%d] number:",++i);
printf("%d\n",this->num);
this=this->next;
}while(this!=0);
}
推荐阅读
void sorting(void)
{
struct datatype *u,*v,*s,*t;
s=h->next;
h->next=null;
while (s!=null ){
for( t=s, v=h,; v!=null && v->num<t->data; u=v, v=v->num )
s=s->next;
if( v==h ) h=t;
else u->next=t;
t->next=v;
}
}
void sorting(void)
{
struct datatype *p, *p1, *temp;
int num;
p1 = p = head;
for(; p; p=p->next)
{
temp = null;
for(p1=p->next; p1; p1=p1->next)
if(p->num > p1->num)
temp = p1;
if(temp != null)
{
num = temp->num;
temp->num = p->num;
p->num = num;
}
}
}