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

来源:互联网 发布:网络机顶盒小米盒子 编辑:程序博客网 时间:2024/04/29 19:08
#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;}
原创粉丝点击