码迷,mamicode.com
首页 > 其他好文 > 详细

[LeetCode] 86. Partition List_Medium tag: Linked List

时间:2019-05-02 11:38:39      阅读:102      评论:0      收藏:0      [点我收藏+]

标签:inpu   gre   大于等于   div   one   node   bsp   link   用两个   

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

标签:inpu   gre   大于等于   div   one   node   bsp   link   用两个   

原文地址:https://www.cnblogs.com/Johnsonxiong/p/10801691.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!