/*程序功能:输入一个链表并按照链表标号排序
*编译环境:VC6.0
*by:spygg
*/
#include<stdio.h>
#include<stdlib.h>
struct list
{
int num;
struct list *next;
};
struct list *creat()//创建链表
{
struct list *head,*p,*tail;
head=NULL;
do
{
printf("input the num (0 as the end)\n");
p=(struct list*)malloc(sizeof(struct list));
if(p==NULL)
{
printf("Memonry malloc failed\n");
exit(0);
}
p->next=NULL;
scanf("%d",&p->num);
if(p->num==0)
{
free(p);
break;
}
if(head==NULL)//第一次开辟的指针赋值给head
{
head=p;
tail=p;
}
else
{
tail->next=p;
tail=p;
}
}while(p->num!=0);
return (head);
}
void print(struct list* head)//打印链表
{
struct list *p;
p=head;
while(p!=NULL)
{
printf("%-3d",p->num);
p=p->next;
}
printf("\n");
}
struct list*sort(struct list*head)
{
struct list *p,*p1,*p2;
int tmp;
for(p=head;p->next!=NULL;p=p->next)
for(p1=p->next;p1!=NULL;p1=p1->next)
{
if(p->num>p1->num)
{
tmp=p->num;
p->num=p1->num;
p1->num=tmp;
}
}
return head;
}
int main(void)
{
struct list *head,*p;
head=creat();
p=head;
print(head);
sort(head);
print(head);
}