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.

解题方法

如果用类似swap的方法太麻烦,可以新建一个list, 用来存原list中小于x的node, 并且将原Node从原list中删去,最后将原List接到新list的后面。

Solution

# Definition for singly-linked list.
# class ListNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution(object):
    def partition(self, head, x):
        """
        :type head: ListNode
        :type x: int
        :rtype: ListNode
        """
        if not head:
            return None

        smallHead = ListNode(0)
        dummy = ListNode(0)
        dummy.next = head
        pre = dummy
        s = smallHead

        while pre.next:
            if pre.next.val < x:
                s.next = pre.next
                pre.next = pre.next.next
                s = s.next
            else:
                pre = pre.next

        s.next = dummy.next

        return smallHead.next

Reference