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,不然会造成链表有环的情况。

 

posted on 2016-05-30 20:12  Sheryl Wang  阅读(123)  评论(0编辑  收藏  举报

导航