1. 程式人生 > >【LeetCode 中等題】44-分隔連結串列

【LeetCode 中等題】44-分隔連結串列

題目描述:給定一個連結串列和一個特定值 x,對連結串列進行分隔,使得所有小於 x 的節點都在大於或等於 x 的節點之前。你應當保留兩個分割槽中每個節點的初始相對位置。

示例:

輸入: head = 1->4->3->2->5->2, x = 3
輸出: 1->2->2->4->3->5

解法1。在現有連結串列的基礎上新建2個連結串列,一個按序儲存小於x的節點,一個儲存>=x的節點,最後把這兩個子連結串列連結起來

# 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
        """
        pre_min = cur_min = ListNode(0)
        pre_max = cur_max = ListNode(0)
        cur = head
        while cur:
            if cur.val < x:
                cur_min.next = cur
                cur_min = cur_min.next
            else:
                cur_max.next = cur
                cur_max = cur_max.next
            cur = cur.next
        cur_min.next = pre_max.next
        cur_max.next = None
        return pre_min.next