链表插入排序

微笑、不失礼 提交于 2020-02-24 16:02:37

单链表插入排序

#include<bits/stdc++.h>
using namespace std;

struct LNode
{
    int data;
    LNode *next;
};
void creathead(LNode *&L,int a[],int n)///尾插法
{
    LNode *r,*s;
    L=(LNode*)malloc(sizeof(LNode));
    L->next=NULL;
    r=L;
    for(int i=0; i<n; i++)
    {
        s=(LNode*)malloc(sizeof(LNode));
        s->data=a[i];
        r->next=s;
        r=r->next;
    }
    r->next=NULL;
}
///插入排序思想
void insertsort(LNode *&L)
{
    LNode *p,*q,*r;
    p=L->next->next;///插入排序从第二个元素开始
    L->next->next=NULL;
    while(p)
    {
        q=p->next;///p接着的元素节点
        r=L;
        while(r->next!=NULL && r->next->data < p->data)///找p应该插入的位置
            r=r->next;
        ///头插
        p->next=r->next;
        r->next=p;
        p=q;///继续下一个
    }
}

int main()
{
    LNode *L,*B;
    int n,c[10000];
    scanf("%d",&n);
    for(int i=0; i<n; i++)
        scanf("%d",&c[i]);
    creathead(L,c,n);
    insertsort(L);
    while(L->next!=NULL)
    {
        printf("%d ",L->next->data);
        L=L->next;
    }
    printf("\n");
    return 0;
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!