C實(shí)例編程:C語(yǔ)言鏈表的創(chuàng)建與排序

字號(hào):

include
    #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(&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;
    }