Python solution with detailed explanation

  • 0


    Swap Nodes in Pairs

    Generalized Solution for K Splits

    • Use the concept of dummy sentinel nodes
    • Create an array of K head nodes and their respective tail pointers
    • Node k gets appended to k%K list.
    • Now create a result dummy node. Iterate the array of tails in reverse order and keep adding row by row.
    class Solution(object):
        def swapPairs(self, head):
            :type head: ListNode
            :rtype: ListNode
            K = 2
            splits = [ListNode(-1) for _ in range(K)]
            tails = [splits[i] for i in range(K)]
            k = 0
            while head:
                temp =
                tails[k % K].next = head
                tails[k % K] = head
       = None
                head = temp
                k = k + 1
            start, tails = ListNode(-1), [splits[i].next for i in range(K)]
            result = start
            while k > 0:
                for i in range(len(tails)-1,-1,-1):
                    if tails[i] != None:
                        temp = tails[i].next
               = tails[i]
                        result = tails[i]
                        tails[i].next = None
                        tails[i] = temp
                        k -= 1

Log in to reply

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