Another python solution


  • 0
    J
    # Definition for singly-linked list.
    # class ListNode(object):
    #     def __init__(self, x):
    #         self.val = x
    #         self.next = None
    
    class Solution(object):
        def reverseKGroup(self, head, k):
            """
            :type head: ListNode
            :type k: int
            :rtype: ListNode
            """
            curr = head
            
            count = 0
            while head:
                count += 1
                head = head.next
            
            rep = count/k
            dummy_res = dummy_res_end = ListNode(0)
            
            for _ in range(rep):
                rev, rev_end = None, curr
                for _ in range(k):
                    next_rev_head = curr
                    curr = curr.next
                    rev, next_rev_head.next = next_rev_head, rev
                
                dummy_res_end.next = rev
                dummy_res_end = rev_end
            dummy_res_end.next = curr
        
            return dummy_res.next
    

Log in to reply
 

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