Python beats 99% solutions


  • 0
    K
    class Solution(object):
        def reverseKGroup(self, head, k):
            """
            :type head: ListNode
            :type k: int
            :rtype: ListNode
            """
            def reverseList(before, begin, end, after):
                """
                Reverse from begin to end, inclusively.
                """
                prev = before
                cur = begin
                while cur != end:
                    nex = cur.next
                    cur.next = prev
                    prev = cur
                    cur = nex
                end.next = prev
                before.next = end
                begin.next = after
            
            if k == 1:
                return head
            dummy = before = ListNode(0)
            dummy.next = begin = cur = head
            while True:
                i = 0
                while i < k - 1 and cur:
                    i += 1
                    cur = cur.next
                # Less than k nodes left or the end node is None
                if i < k - 1 or not cur:
                    break
                end = cur
                after = cur.next
                reverseList(before, begin, end, after)
                before = begin
                begin = cur = after
            return dummy.next
    

Log in to reply
 

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