Partition List

这道题需要理解清楚题目的意思,题目说的是小于这个基准值的全部拉到前面去,而不小于这个值的相对位置全部不动,这样我们其实可以利用一个临时的链表把所有小于基准值的结点全部从当前链表解开连到这个新链表上面去,这样我们就能保持相对位置了

# 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
        """
        dummy = ListNode('d')
        dummy.next = head
        cur = dummy
        left = ListNode('d')
        leftCur = left

        while cur.next:
            if cur.next.val < x:
                tmp = cur.next
                cur.next = cur.next.next
                leftCur.next = tmp
                leftCur = leftCur.next
            else:
                cur = cur.next

        leftCur.next = dummy.next
        return left.next

results matching ""

    No results matching ""