单链表排序问题(冒泡/快排【前后指针法】)

#include<iostream>
#include<assert.h>
using namespace std;
typedef struct Node
{
    int data;
    struct Node* next;
    Node(int x)
        :data(x)
        ,next(NULL)
    {}
}Node;


----------//核心代码


//1.冒泡排序
void BubbleSortList(Node* PHead)
{
    //为空或者只有一个结点,直接返回
     if (PHead==NULL||PHead->next==NULL)
     {
         return;
     }
     //不为空,大于一个结点
     Node* cur=NULL;
     Node* next=NULL;
     Node* Tail=NULL;
     while(Tail!=PHead)
     {
         Node* cur=PHead;
         Node* next=PHead->next;
         int  mark=0;//标志
         while(next!=Tail)
         {
             if (cur->data>next->data)
             {
                 std::swap(cur->data,next->data);
                 mark=1;
              }
             cur=next;
             next=cur->next;
         }
         if (mark=0)
         {
             break;
         }
         Tail=cur;
     }

}


----------


----------//核心代码


//快排--前后指针法(因为不能从后往前遍历链表)
void QuickSort(Node* PHead,Node*  Tail)//将链表区间的最后一个结点的next作为结束标志
{
    if (PHead==NULL||PHead->next==Tail||PHead==Tail)
    {
        return ;
    }
    Node* cur=PHead->next;//前指针
    Node* prev=PHead;//后指针
    int key=prev->data;//将链表区间的第一个数作为基准值
    while(cur!=Tail)//一趟排序的结束条件---就是前指针已经走到区间末尾的下一个位置
    {   
        if (cur->data<key)//cur遇到了比key小的数,则将prev先后走一步,交换值
        {
            prev=prev->next;
            if (prev!=cur)
            {
                std::swap(cur->data,prev->data);
            }
        }
        cur=cur->next;//cur继续向后走
    }
    //循环出来以后将基准值和prev当前的结点值作交换
    std::swap(PHead->data,prev->data);
    QuickSort(PHead,prev);
    QuickSort(prev->next,Tail);
}


----------


void Printf(Node* PHead)
{
    assert(PHead);
    Node* cur=PHead;
    while (cur)
    {
        cout<<cur->data<<" ";
        cur=cur->next;
    }
}
int main()
{
        Node* node1 = new Node(4);
        Node* node2 = new Node(9);
        Node* node3 = new Node(3);
        Node* node4 = new Node(5);
        node1->next = node2;
        node2->next = node3;
        node3->next = node4;

        BubbleSortList(node1);
        cout<<"冒泡";
        Printf(node1);
        cout<<endl;
        QuickSort(node1,NULL);
        cout<<"快排";
        Printf(node1);
    return 0;
}
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值