吉大考研复试准备-用数组冒泡排序的思想对链表排序(带哨兵结点)

思路如下:

  1. 首先 遍历链表,得到结点个数count,不包括哨兵结点
  2. for大循环,while小循环。其中for循环的i是为了限制while循环的每一趟的循环次数num,考虑对数组进行的冒泡排序,n个元素进行排序,第一趟n-1次比较,第二趟n-2次,。。最后之比较一次。
  3. 代码如下
    #include <stdio.h>
    #include<stdlib.h>
    typedef struct LinkNode
    {
        int data;
        struct LinkNode*next;
    }node;
    
    node* create();//创建带哨兵结点的链表
    node* bubble(node*head);//对链表进行冒泡排序
    void printfList(node*head);//输出链表
    
    int main()
    {
        node*head=create();
        bubble(head);
        printfList(head);
    }
    
    node* create()
    {
        node*head=(node*)malloc(sizeof(node));
        head->next=NULL;
        node*tail=head;
    
        int x;
        scanf("%d",&x);
        while(x!=-1)
        {
            node*p=(node*)malloc(sizeof(node));
            p->data=x;
            p->next=tail->next;
            tail->next=p;
            tail=tail->next;
    
            scanf("%d",&x);
        }
    
        return head;
    }
    
    node* bubble(node*head)
    {
        node*p=head->next;
        int count=0;//统计节点个数
        while(p!=NULL)
        {
            count++;
            p=p->next;
        }
    
        for(int i=0;i<count-1;i++)
        {
            int num=count-1-i;//限制while循环次数
            node*front=head;
            node*p=head->next;
            node*q=p->next;
    
            while(num!=0)
            {
                if(p->data>q->data)
                {
                    p->next=q->next;
                    front->next=q;
                    q->next=p;
    
                    front=front->next;
                    q=p->next;
                }
                else{
                    front=front->next;
                    p=p->next;
                    q=q->next;
                }
                num--;
            }
        }
    
        return head;
    }
    
    void printfList(node*head)
    {
        node*p=head->next;
        while(p!=NULL)
        {
            printf("%d ",p->data);
            p=p->next;
        }
    }
    

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值