C语言链表的创建与排序
include<stdio.h>
#include<stdlib.h>
typedef struct STRUCT {
int value;
struct STRUCT *next;
}TS;
main()
{
#define N 9
int a[N],i;
TS *head,*p;
TS *CreateLink(int *,int);
void sort(TS **);
randomize();
for(i=0;i a=random(9);
head=CreateLink(a,N);
for(p=head;p;p=p->next)
printf("%-2d",p->value);
putchar('\n');
sort(&head);
for(p=head;p;p=p->next)
printf("%-2d",p->value);
getchar();
}
void sort(TS **h) /* 选择排序算法 */
{
TS *h1,*p,*q,*r,*s;
h1=p=(TS *)malloc(sizeof(TS));
p->next=*h;
while(p->next) {
q=p->next;
r=p;
while(q->next) {
if(q->next->valuenext->value)
r=q;
q=q->next;
}
if(r!=p) {
s=r->next;
r->next=s->next;
s->next=p->next;
p->next=s;
}
p=p->next;
}
*h=h1->next;
free(h1);
}
TS *CreateLink(int *a,int n)
{
int i;
TS *h,*p;
h=NULL;
for(i=n;i>0;i--) {
p=(TS *)malloc(sizeof(TS));
p->value=a[i-1];
p->next=h;
h=p;
}
return h;
}