Simple python code beats 99.28% , with comment


  • 0
    3
    class Solution(object):
        def reverseKGroup(self, head, k):
            """
            :type head: ListNode
            :type k: int
            :rtype: ListNode
            """
            if head==None:
                return None
            ret=head
            nxt=ret.next
            tail=head
            for i in range(1,k):
                if nxt==None:
                    #hit the end of list, reversing
                    rev_head=ret
                    rev_nxt=ret.next
                    ret.next=None  #prevent the occurrence of loop in the list 
                    for k in range(i-1):
                        tmp=rev_nxt.next
                        rev_nxt.next=rev_head
                        rev_head=rev_nxt
                        rev_nxt=tmp
                    return rev_head
                    break
                tmp=nxt.next
                nxt.next=ret
                ret=nxt
                nxt=tmp
           
           #recursively reversing the list
            tail.next=self.reverseKGroup(nxt,k)
            return ret
    

Log in to reply
 

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