Python solution O(n) and just 76ms


  • 0
    S
    class Solution(object):
        def reverseKGroup(self, head, k):
            """
            :type head: ListNode
            :type k: int
            :rtype: ListNode
            """
            root = ListNode(0)
            root.next = head
            point = root 
            end_point = point
            while 1:
                n = 0
                while n!=k:
                    end_point = end_point.next
                    if not end_point: return root.next
                    n+= 1
                temp = end_point
                end_point = end_point.next
                p1 = point.next
                p2 = point.next.next
                p1.next = end_point
                point.next = temp
                next_point = p1
                for i in range(k-1):
                    temp = p2.next
                    p2.next = p1
                    p1 = p2
                    p2 = temp
                point = end_point = next_point
                
    

Log in to reply
 

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