代码改变世界

[LeetCode] 86. Partition List_Medium tag: Linked List

2019-05-02 09:57  Johnson_强生仔仔  阅读(253)  评论(0编辑  收藏  举报

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.

Example:

Input: head = 1->4->3->2->5->2, x = 3
Output: 1->2->2->4->3->5

这个题目就是利用两个dummy node,leftDummy 代表小于x的那些node,rightDummy 代表大于等于x的那些node,最后将两者加起来即可。

Note: 最后要将right.next = None 

Code

class ListNode:
    def __init__(self, x):
        self.val = x
        self.next = None

class Solution:
    def partitionList(self, head, x):
        leftDummy, rightDummy = ListNode(0), listNode(0)
        left, right = leftDummy, rightDummy
        while head:
            if head.val < x:
                left.next = head
                left = left.next
            else:
                right.next = head
                right = right.next
            head = head.next
        left.next = rightDummy.next
        right.next = None
        return leftDummy.next