11-line one-pass, easy to understand Python solution

  • 4
    class Solution(object):
        def partition(self, head, x):
            :type head: ListNode
            :type x: int
            :rtype: ListNode
            left, right = ListNode(None), ListNode(None)
            left_cur, right_cur = left, right
            while head:
                if head.val < x:
                    left_cur.next, head = head, head.next
                    left_cur, left_cur.next = left_cur.next, None
                    right_cur.next, head = head, head.next
                    right_cur, right_cur.next = right_cur.next, None
            left_cur.next = right.next
            return left.next

Log in to reply

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