【數據結構】單鏈表—排序

使單鏈表遞增有序

代碼如下

#include<stdio.h>
#include<stdlib.h>
struct Lnode
{
    int data;
    Lnode *next;
};
int Init(struct Lnode *L, int i)
{
    struct Lnode *p;
    struct Lnode *q=L;
    int j=0;
    while(j<i)
    {
        p = (struct Lnode *)malloc(sizeof(struct Lnode));
        scanf("%d",&(p->data));
        p->next =NULL;
        q->next = p;
        q= p;
        j++;
    }
    return 0;
}
int sort(struct Lnode *L)
{
    if(L->next==NULL)
        return 0;
    struct Lnode *p = (L->next)->next;
    struct Lnode *q,*i;
    (L->next)->next = NULL;
    while(p!=NULL)
    {
        q = p->next;
        i = L;
        while(i->next!=NULL&&(i->next)->data<p->data)
            i = i->next;
        p->next = i->next;
        i->next=p;
        p = q;
    }
    return 0;
}
int main()
{
    struct Lnode Head;
    struct Lnode *L=&Head;
    L->next = NULL;
    int i = 5;
    Init(L,i);
    sort(L);
    struct Lnode *p = L->next;
    while(p!=NULL)
    {
        printf("%d",p->data);
        p = p->next;
    }
    return 0;
}    
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章