c++ 链表partition代码(类似快排操作)

分三个区域,小中大,然后依次连接返回小中大最先非空的头指针

#include <iostream>
using namespace std;
class Node
{
public:
    int value;
    Node* next;
    Node()
    {
        value = 0;
        next = NULL;
    }
    Node(int value)
    {
        this->value = value;
        this->next = NULL;
    }
};
Node* partition(Node* head, int part)
{
    Node* sH = NULL;
    Node* sT = NULL;
    Node* eH = NULL;
    Node* eT = NULL;
    Node* bH = NULL;
    Node* bT = NULL;
    Node* next = NULL;
    while (head != NULL)
    {
        next = head->next;
        head->next = NULL;       //让节点以单一形式进入partition
        if (head->value < part)
        {
            if (sH == NULL)
            {
                sH = head;
                sT = head;
            }
            else
            {
                sT->next = head;
                sT = head;
            }
        }
        else if (head->value == part)
        {
            if (eH == NULL)
            {
                eH = head;
                eT = head;
            }
            else
            {
                eT->next = head;
                eT = head;
            }
        }
        else if (head->value > part)
        {
            if (bH == NULL)
            {
                bH = head;
                bT = head;
            }
            else
            {
                bT->next = head;
                bT = head;
            }
        }
        head = next;
    }
    if (sT != NULL)
    {
        sT->next = eH;
        eT = eT == NULL ? sT : eT;       //不存在的话,中尾换回小尾
    }
    if (eT != NULL)
    {
        eT->next = bH;
    }
    return sH!=NULL?sH:(eH!=NULL?eH:bH);      //返回非空最初始非空节点
}
void showList(Node* head)
{
    while (head != NULL)
    {
        cout << head->value << ' ';
        head = head->next;
    }
}
int main()
{
    Node* node=new Node(100);
    node->next = new Node(0);
    Node* head = node;
    for (int i = 5; i < 80; i = i*2-3)
    {
        node = node->next;
        node->next = new Node(i);
    }
    showList(head);
    cout << endl << "*******************" << endl;
    head = partition(head, 13);
    showList(head);
    return 0;
}

输出:

100 1 5 7 11 19 35 67
*******************
1 5 7 11 100 19 35 67

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值