[LeetCode 86] Partition List

Given a linked list and a value x, partition it such that all nodes less than x come before nodes greater than or equal to x.

You should preserve the original relative order of the nodes in each of the two partitions.

For example, Given 1->4->3->2->5->2 and x = 3, return 1->2->2->4->3->5.

Diffculty
Medium

Similar Problems

Analysis

划分链表相当于一个局部排序的问题。

思路一 从左往右扫描,找到第一个大于 X 的指针,然后再该指针左边,不断插入小于 X 的元素。 这里为了避免处理head是否为空的检测,在头指针位置先插入一个 dummy node,以保证 head 永不为空,然后在最后返回的时候删除掉。

这种思路下,链表变化顺序为:

1 -> 4 -> 3 -> 2 -> 5 -> 2 
1 -> 2 -> 4 -> 3 -> 5 -> 2 
1 -> 2 -> 2 -> 4 -> 3 -> 5

思路二 将所有小于给定值的节点取出组成一个新的链表,此时原链表中剩余的节点的值都大于或等于给定值,只要将原链表直接接在新链表后即可

此种思路下,链表变化顺序为:

Original: 1 -> 4 -> 3 -> 2 -> 5 -> 2 
New:

Original: 4 -> 3 -> 2 -> 5 -> 2 
New:   1

Original: 4 -> 3 -> 5 -> 2 
New:   1 -> 2

Original: 4 -> 3 -> 5 
New:   1 -> 2 -> 2

Original: 
New:   1 -> 2 -> 2 -> 4 -> 3 -> 5 
Solutions

解法一

class Solution {
public:
    ListNode *partition(ListNode *head, int x) {
        ListNode *dummy = new ListNode(-1);
        dummy->next = head;
        ListNode *pre = dummy, *cur = head;
        while (pre->next && pre->next->val < x) // 找到比 x 大的节点
            pre = pre->next;
        cur = pre;              // 此时, pre->next 比 x 大
        while (cur->next) {     // 继续找一个比 x 小的节点,插入到 pre 之前。
            if (cur->next->val < x) { // 找到了 cur->next 比 x 小,把它插入 pre->next 之前
                ListNode *tmp = cur->next;
                cur->next = tmp->next;
                tmp->next = pre->next;
                pre->next = tmp;
                pre = pre->next;
            } else {
                cur = cur->next;
            }
        }
        return dummy->next;
    }
};

解法二

```cpp
class Solution {
public:
    ListNode *partition(ListNode *head, int x) {
        if (!head) return head;
        ListNode *dummy = new ListNode(-1);
        ListNode *newDummy = new ListNode(-1);
        dummy->next = head;
        ListNode *cur = dummy, *p = newDummy;
        while (cur->next) {
            if (cur->next->val < x) {
                p->next = cur->next;
                p = p->next;
                cur->next = cur->next->next;
                p->next = NULL;
            } else {
                cur = cur->next;
            }
        }
        p->next = dummy->next;
        return newDummy->next;
    }
};

results matching ""

    No results matching ""