zoukankan      html  css  js  c++  java
  • 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.

    分割链表,这题看描述极容易想起用快排的partition的方法去做,但是看题目描述需要保存结点原本的相对关系,即需要具有稳定排序的特点,但是快排的partition本身不具有稳定性,为了减少交换的次数,会移动数字在数组的相对位置。

    所以得另想他法,想到的一个办法是,维护两个链表,一个存储比x小的结点,另外一个存储比x大的结点。处理完之后需要将链表1接到链表2,注意因为需要先序结点,dummy node 大法还是需要的,代码如下:

    class Solution(object):
        def partition(self, head, x):
            """
            :type head: ListNode
            :type x: int
            :rtype: ListNode
            """
            if not head:
                return None
            pre1 = dummy1 = ListNode(-1)
            pre2 = dummy2 = ListNode(-2)
            while head:
                if head.val < x:
                    pre1.next = head
                    pre1 = head
                else:
                    pre2.next = head
                    pre2 = head
                head = head.next
                
            pre2.next = None      
            pre1.next = dummy2.next
            
            return dummy1.next

    以上代码一定要注意,需要将pre2.next 置为None,即链表2的尾结点的next为None,不然会造成链表有环的情况。

  • 相关阅读:
    【模板】O(nlongn)求LIS
    【图论】用线段树写Dijikstra!!
    【图论】最短路总结
    【codeforces841A】Generous Kefa
    【模板】Tarjian求LCA
    【模板】 RMQ求区间最值
    【模板】map入门
    【二分 贪心】覆盖问题 BZOJ1052 HAOI2007
    【dp】10-15题解 snake vs block
    【模拟】10-15 题解 trans
  • 原文地址:https://www.cnblogs.com/sherylwang/p/5543777.html
Copyright © 2011-2022 走看看