Python solution with detailed explanation


  • 0
    G

    Solution

    Swap Nodes in Pairs https://leetcode.com/problems/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 = head.next
                tails[k % K].next = head
                tails[k % K] = head
                head.next = 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
                        result.next = tails[i]
                        result = tails[i]
                        tails[i].next = None
                        tails[i] = temp
                        k -= 1
            return start.next
    

Log in to reply
 

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