Using a pointer to record last node that is smaller than x

  • 0
    class Solution:
        # @param {ListNode} head
        # @param {integer} x
        # @return {ListNode}
        def partition(self, head, x):
            current = head
            prev = ListNode(-1)
   = head
            #Mark the last node that is smaller than x
            last = head = prev
            while current:
                if current.val >= x:
                #Move prev and current forward if current value is not smaller than x, last remains the same
                    prev = current
                    current =
                    if prev == last:
                        #Move last, prev and current forward 
                        prev = last = current
                        current =
                        #Put the current node between last and
               = current
                        #Update last and current, prev remains the same
                        last = current
                        current =

Log in to reply

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