Easy -to-understand Python

  • 0
    def partition(self, head, x):
        d1 = large = ListNode(-1)
        d2 = small = ListNode(0)
        cur = head
        while cur:
            if cur.val < x:
                small.next = cur
                small = small.next
                large.next = cur
                large = large.next
            cur = cur.next
        large.next = None
        small.next = d1.next
        return d2.next

    Define two dummy nodes, two cursors 'large' and 'small' collecting elements larger than x and smaller than x respectively. Another cursor starts from head, going through the list. Each element that 'cur' goes through, gets linked by 'large' or 'small' accordingly.

Log in to reply

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.