Python solution 81ms, O(n) time, constance memory space


  • 0
    H
    class Solution(object):
        def reverseKGroup(self, head, k):
            """
            :type head: ListNode
            :type k: int
            :rtype: ListNode
            """
            if not head or k==1:
                return head
            ptr = head
            num = 0
            while ptr:
                ptr = ptr.next
                num += 1
            if num < k:
                return head
            preNode = ListNode(0)
            preNode.next = head
            
            before = preNode
            print(num)
            while num >= k:
                pre = before.next
                cur = pre.next
                for _ in range(k-1):
                    post = cur.next
                    cur.next = pre
                    pre = cur
                    cur = post
                new_tail = before.next
                new_tail.next = cur
                before.next = pre
                
                before = new_tail
                num -= k
                # self.print_list(preNode.next)
            return preNode.next
    

Log in to reply
 

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