链表分割

题目描述

以给定值x为基准将链表分割成两部分,所有小于x的结点排在大于或等于x的结点之前

给定一个链表的头指针 ListNode* pHead,请返回重新排列后的链表的头指针。注意:分割以后保持原来的数据顺序不变。

ListNode* partition(ListNode* pHead, int x) {
        // write code here
        if (pHead == NULL || pHead->next == NULL) return pHead;
        
        ListNode* small=new ListNode(0);
        ListNode* big=new ListNode(0);
        ListNode *ps=small,*pb=big,*cur=pHead;
        
        while(cur)
        {
            if(cur->val<x)
            {
                ps->next=cur;
                ps=cur;
            }
            else
            {
                pb->next=cur;
                pb=cur;
            }
            cur=cur->next;
        }
        pb->next=nullptr;
        ps->next=big->next;
        return small->next;
    }
原文地址:https://www.cnblogs.com/wang-130213/p/9073152.html