Simple Python O(n). Shift Nodes to End


  • 0
        def partition(self, head, x):
            if not head: return 
            buffr = prev = ListNode(None)
            buffr.next = end = head
            lng = 0
            while end.next: # look for end point
                end = end.next
                lng += 1
            while head and lng >= 0: # grow list at end if value >= x is found
                lng -= 1
                if head.val >= x:
                    end.next = end = head
                    prev.next = head = head.next
                    end.next = None
                else:
                    prev, head = head, head.next
            return buffr.next
    

Log in to reply
 

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