[leetcode_86]Partition List

单链表划分。选择一个 val x 然后单链表中比 x 值小的节点在前,大的在后,但是小与小,大与大之间保持原位置。
想法:
先找到第一个比 x 小的值,放到最前面。
再找到第一个比 x 大的值。
接下来就是从 x 大的值的节点后面开始枚举,大的继续,出现小的,交换到第一个比 x 大的值前面。

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
class Solution {
public:
    ListNode *partition(ListNode *head, int x) {
        if(head == NULL || head->next == NULL)
            return head;
        ListNode * beforenode;
        ListNode * minnode, *maxnode; // find the 1st minnode
        if(head->val < x) {
            minnode = head;
        }
        else {
            beforenode = head;
            minnode = head->next;
            while(minnode != NULL && minnode->val >= x) {
                beforenode = minnode;
                minnode = minnode->next;
            }
            if(minnode == NULL) return head;
            beforenode->next = minnode->next;
            minnode->next = head; // now the head is minnode;
        }
        beforenode = minnode;
        maxnode = minnode->next;
        while(maxnode != NULL && maxnode->val < x) {
            beforenode = maxnode;
            maxnode = maxnode->next;
        }
        if(maxnode == NULL || maxnode->next == NULL) return minnode;
        // now find minnode and maxnode. the head is minnode
        head = minnode;
        ListNode * now = maxnode->next;
        while(now != NULL) {
            if(now->val >= x) {
                maxnode = now;
                now = now->next;
            }
            else {
                ListNode * tmp = beforenode->next;
                maxnode->next = now->next;
                beforenode->next = now;
                now->next = tmp;
                now = maxnode->next;
                beforenode = beforenode->next;
            }
        }
        return head;
    }
};
Licensed under CC BY-NC-SA 4.0