Python Non recursive solution, easy understand.68 ms


  • 2
    H
    # pre alway point the last one in previous KGoup. 
    # Constant insert cur kGroup's node after it.
    class Solution(object): 
    def reverseKGroup(self, head, k):
        pre, pre.next = self, head
        while self.needReverse(head, k):
            tail = head  # 1st one in cur KGroup
            for _ in xrange(k):
                pre.next, head.next, head = head, pre.next, head.next
            pre = tail  # now, it become the last one in previous KGroup 
        pre.next = head  #maybe there are some rest node.
        return self.next
        
    def needReverse(self, head, k):
        while head and k:
            k -= 1
            head = head.next
        return k == 0
    
    # 68 ms, 81 / 81 test cases passed.
    # beats 84.43% of python submissions.

  • 0
    W

    really consice


Log in to reply
 

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