Python Non recursive solution, easy understand.68 ms

  • 2
    # 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, = self, head
        while self.needReverse(head, k):
            tail = head  # 1st one in cur KGroup
            for _ in xrange(k):
      ,, head = head,,
            pre = tail  # now, it become the last one in previous KGroup = head  #maybe there are some rest node.
    def needReverse(self, head, k):
        while head and k:
            k -= 1
            head =
        return k == 0
    # 68 ms, 81 / 81 test cases passed.
    # beats 84.43% of python submissions.

  • 0

    really consice

Log in to reply

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