Python Solution, simple with comments, beats 78%.


  • 0
    M

    '''

    def reverseKGroup(self, head, k):
        """
        :type head: ListNode
        :type k: int
        :rtype: ListNode
        """
        
        Head = None # return node
        preTail = None # previous tail
        nextHead = head # next node to be reversed
        while nextHead:
            # head is the head of the reversed linked list
            # tail is the tail of ~~
            # nnode is the next node succeed ~~
            # r is the remaining length (r > 0 if insufficient)
            head, tail, nextHead, r = self.reverse(nextHead, k)
            if r > 0: # if insufficient
                head, tail, nextHead, r = self.reverse(head, k-r) # reverse list back to original order
            if preTail: 
                preTail.next = head
            else: # first segment
                Head = head
            preTail = tail
        return Head
        
        
    def reverse(self, head, k):
        """
        :type head: ListNode
        :type k: int
        :rtype head: ListNode
        :rtype tail: ListNode
        """
        
        p0 = None
        p1 = head
        
        while p1 and k:
            p2 = p1.next
            p1.next = p0
            p0, p1 = p1, p2
            k -= 1
        return p0, head, p1, k
        
        '''

Log in to reply
 

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