机动车未贴年检的处罚:单链表排序问题(C语言)

来源:百度文库 编辑:高考问答 时间:2024/04/20 15:10:05
做联系遇到困难了 想了一下午也没做出来
希望能给提供点算法或是相关例题!谢谢

经典算法--单链表选择排序第一种:
#include<stdio.h>
#include<stdlib.h>
typedef struct node{
int data;
struct node *next;
}*Linklist,Node;
Linklist creat(int n)
{Linklist head,r,p;
int x,i;
head=(Node*)malloc(sizeof(Node));
r=head;
printf("输入数字:\n");
for(i=n;i>0;i--)
{scanf("%d",&x);
p=(Node*)malloc(sizeof(Node));
p->data=x;
r->next=p;
r=p;}
r->next=NULL;
return head;
} void output(Linklist head)
{Linklist p;
p=head->next;
do{
printf("%3d",p->data);p=p->next;
}while(p);
printf("\n");
} void paixu(Linklist head)
{Linklist p,q,small;int temp;

for(p=head->next;p->next!=NULL;p=p->next)
{small=p;
for(q=p->next;q;q=q->next)
if(q->data<small->data)
small=q;
if(small!=p)
{temp=p->data;
p->data=small->data;
small->data=temp;}
} printf("输出排序后的数字:\n");
output(head);
} void main()
{Linklist head;
int x,j,n;
printf("输入数字的个数(n):\n");
scanf("%d",&n);
head=creat(n);
printf("输出数字:\n");
output(head);
printf("已排序的数字:\n");
paixu(head);
}
第二种:
#include<stdio.h>
#include<stdlib.h>
typedef struct node{
int data;
struct node *next;
}*Linklist,Node;
Linklist creat(int n)
{Linklist head,r,p;
int x,i;
head=(Node*)malloc(sizeof(Node));
r=head;
printf("输入数字:\n");
for(i=n;i>0;i--)
{scanf("%d",&x);
p=(Node*)malloc(sizeof(Node));
p->data=x;
r->next=p;
r=p;}
r->next=NULL;
return head;
} Linklist selectsort(Node *g)
{ Node *p,*q,*t,*s,*h;
h=(Node *)malloc(sizeof(Node));
h->next=g;
p=h;
while(p->next->next!=NULL)
{
for(s=p,q=p->next;q->next!=NULL;q=q->next)
if(q->next->data<s->next->data)
s=q;
if(s!=q)
{
t=s->next;
s->next=t->next;
t->next=p->next;
p->next=t;
}
p=p->next;
}
g=h->next;
free(h);
return g;
} void output(Linklist head)
{Linklist p;
p=head->next;
do{
printf("%3d",p->data);p=p->next;
}while(p);
printf("\n");
} void main()
{Linklist head;
int x,j,n;
printf("输入数字的个数(n):\n");
scanf("%d",&n);
head=creat(n);
printf("输出数字:\n");
output(head);
head=selectsort(head);
printf("已经排序的数字:\n");
output(head);
}