[LeetCode] 86. Partition List_Medium tag: Linked List

Posted johnsonxiong

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[LeetCode] 86. Partition List_Medium tag: Linked 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.

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,最后将两者加起来即可。

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

 

以上是关于[LeetCode] 86. Partition List_Medium tag: Linked List的主要内容,如果未能解决你的问题,请参考以下文章

Leetcode 86. Partition List

Leetcode 86. Partition List

Leetcode 86. Partition List

LeetCode86 Partition List

leetcode86 - Partition List - medium

[LeetCode] 86. Partition List Java