Pythonic solution, 76-80 ms, no if-then-else at all, o(n) time, o(k) space


  • 0
    B
    class Solution:
    # @param {ListNode} head
    # @param {integer} k
    # @return {ListNode}
    def reverseKGroup(self, head, k):
        p0 = guard = ListNode(0)
        guard.next = head
        try:
            while True:
                p, pointers = p0, list()
                for _ in range(k):
                    p = p.next
                    pointers.append(p)
                    
                pointers[0].next = pointers[-1].next
                for i in range(len(pointers)-1,0,-1):
                    pointers[i].next = pointers[i-1]
                p0.next = pointers[-1]
                p0 = pointers[0]
        except:
            return guard.next

Log in to reply
 

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