/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */
class Solution {
public:
    ListNode* partition(ListNode* head, int x) {
        if(!head) return head;
        if(!head->next) return head;
        ListNode* less = NULL,*more = NULL,*cur = head;
        while(cur) {
            if(cur->val<x&&!less)
                less = cur;
            if(cur->val>=x&&!more)
                more = cur;
            cur = cur->next;
        }
        ListNode* lesstag = less,*moretag = more;
        cur = head;
        while(cur) {
            if(cur!=lesstag&&cur->val<x) {
                less->next = cur;
                less = less->next;
            }
            if(cur!=moretag&&cur->val>=x) {
                more->next = cur;
                more = more->next;
            }
            cur = cur->next;
        }
        //特殊情况需要注意
        if(more)
            more->next = NULL;
        if(!less)
            return moretag;
        less->next = moretag;
        
        return lesstag;
    }
};

分析

单链表的partion:可以采用放入数组再重新连接的方式但是o(N)的空间
优化空间的话就是类似的方式按照分发包的方式,先找到第一个小于x和第一个大于等于x的结点,一定是找到第一个因为需要保持稳定,然后再遍历的时候就一个判断将每个结点发到对应该去的链表。最后再将两个链表连在一起,注意可能会出现有一个链表不存在的特殊情况,需要加上判断,然后尾部记得连上空。