[LeetCode] 86. Partition List 分隔链表

 

Given the head of 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.

Example 1:

Input: head = [1,4,3,2,5,2], x = 3
Output: [1,2,2,4,3,5]

Example 2:

Input: head = [2,1], x = 2
Output: [1,2]

Constraints:

  • The number of nodes in the list is in the range [0, 200].
  • -100 <= Node.val <= 100
  • -200 <= x <= 200

 

这道题要求我们划分链表,把所有小于给定值的节点都移到前面,大于该值的节点顺序不变,相当于一个局部排序的问题。那么可以想到的一种解法是首先找到第一个大于或等于给定值的节点,用题目中给的例子来说就是先找到4,然后再找小于3的值,每找到一个就将其取出置于4之前即可,代码如下:

 

解法一:

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) pre = pre->next;
        cur = pre;
        while (cur->next) {
            if (cur->next->val < x) {
                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;
    }
};

 

这种解法的链表变化顺序为:

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

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

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

 

此题还有一种解法,就是将所有小于给定值x的结点取出组成一个新的链表 list1,将大于等于给定值x的结点都取出来组成另一个链表 list2,将此时链表 list2 中结点的值都大于或等于给定值x,只要将 list2 链表直接接在 list1 链表后即可,此种解法链表变化顺序为:

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

List1 :   4 -> 3 -> 5 

List2 :   1 -> 2 -> 2

Result:  1 -> 2 -> 2 -> 4 -> 3 -> 5 

 

解法二: 

class Solution {
public:
    ListNode* partition(ListNode* head, int x) {
        ListNode *node1 = new ListNode(-1), *node2 = new ListNode(-1);
        ListNode *p1 = node1, *p2 = node2;
        while (head) {
            if (head->val < x) {
                p1->next = head;
                p1 = p1->next;
            } else {
                p2->next = head;
                p2 = p2->next;
            }
            head = head->next;
        }
        p2->next = NULL;
        p1->next = node2->next;
        return node1->next;
    }
};

 

Github 同步地址:

https://github.com/grandyang/leetcode/issues/86

 

类似题目:

Partition Array According to Given Pivot

 

参考资料:

https://leetcode.com/problems/partition-list

https://leetcode.com/problems/partition-list/solutions/29185/very-concise-one-pass-solution/

 

LeetCode All in One 题目讲解汇总(持续更新中...)

posted @ 2015-03-08 08:37  Grandyang  阅读(14696)  评论(0编辑  收藏  举报
Fork me on GitHub