链表排序

#include<stdio.h>
#include<stdlib.h>
#define N 5
#define NULL 0
#define OK 1
#define ERROR 0

typedef struct LNode
{
    struct LNode *next;
    int data;
}LNode,*list;

void creatList(list &l,int n)
{
    list p,q;
    l=(list)malloc(sizeof(LNode));
    p=l;
    for(int i=0;i<n;i++)
    {
        q=(list)malloc(sizeof(LNode));
        scanf("%d",&q->data);
        p->next=q;
        p=q;
    }
    p->next=NULL;
}

void sortList(list &l)
{
    int change;
    list p,q,r;
    p=l->next;
    while(p->next!=NULL)
    {
        q=l->next;
        while(q->next!=NULL)
        {
            r=q->next;
            if(r->data<q->data)
            {
                change=r->data;
                r->data=q->data;
                q->data=change;
            }
            q=q->next;
        }
        p=p->next;
    }
}

void printList(list l)
{
    list p;
    p=l->next;;
    while(p)
    {
        printf("%d ",p->data);
        p=p->next;
    }
}

int main()
{
    list l;
    printf("input a list contain %d numbers:\n",N);
    creatList(l,N);
    sortList(l);
    printf("sorted List:\n");
    printList(l);
    return 0;

}


你可能感兴趣的:(链表)