
C实例编程-C语言链表的创建与排序.docx
4页C实例编程:C语言链表的创建与排序#include 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( 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; }。
