KatInterview

24. Swap Nodes in Pairs

MediumSolutions in Python, Java, C++, TypeScript

Read the full problem statement on LeetCode and try it first. Below is how to approach it in an interview, followed by a complete answer in each language.

Approach

The problem requires us to swap every two adjacent nodes in a given singly-linked list. A key constraint is that we cannot just swap the values within the nodes; we must change the node pointers themselves. This means we'll be re-wiring the list. For example, a list 1 -> 2 -> 3 -> 4 should become 2 -> 1 -> 4 -> 3. A special case is the head of the list, which will change if a swap occurs at the beginning.

Solution

Swap Nodes in Pairs in Python

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next
class Solution:
    def swapPairs(self, head: Optional[ListNode]) -> Optional[ListNode]:
        # Create a dummy node to act as the predecessor of the head.
        # This simplifies handling the head of the list.
        dummy = ListNode(0, head)
        
        # prev_node is the node just before the pair to be swapped.
        prev_node = dummy
        
        # We need at least two nodes after prev_node to perform a swap.
        while prev_node.next and prev_node.next.next:
            # Nodes to be swapped
            first_node = prev_node.next
            second_node = prev_node.next.next
            
            # Swapping logic
            # 1. prev_node's next should point to the second node
            prev_node.next = second_node
            # 2. first_node's next should point to the node after the second node
            first_node.next = second_node.next
            # 3. second_node's next should point to the first node
            second_node.next = first_node
            
            # Move prev_node for the next pair. After swapping, first_node is the new end of the pair.
            prev_node = first_node
            
        # The new head is dummy.next.
        return dummy.next

Swap Nodes in Pairs in Java

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode() {}
 *     ListNode(int val) { this.val = val; }
 *     ListNode(int val, ListNode next) { this.val = val; this.next = next; }
 * }
 */
class Solution {
    public ListNode swapPairs(ListNode head) {
        // Create a dummy node to act as the predecessor of the head.
        // This simplifies handling the head of the list.
        ListNode dummy = new ListNode(0);
        dummy.next = head;
        
        // prevNode is the node just before the pair to be swapped.
        ListNode prevNode = dummy;
        
        // We need at least two nodes after prevNode to perform a swap.
        while (prevNode.next != null && prevNode.next.next != null) {
            // Nodes to be swapped
            ListNode firstNode = prevNode.next;
            ListNode secondNode = prevNode.next.next;
            
            // Swapping logic
            // 1. prevNode's next should point to the second node
            prevNode.next = secondNode;
            // 2. firstNode's next should point to the node after the second node
            firstNode.next = secondNode.next;
            // 3. secondNode's next should point to the first node
            secondNode.next = firstNode;
            
            // Move prevNode for the next pair. After swapping, firstNode is the new end of the pair.
            prevNode = firstNode;
        }
        
        // The new head is dummy.next.
        return dummy.next;
    }
}

Swap Nodes in Pairs in C++

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode() : val(0), next(nullptr) {}
 *     ListNode(int x) : val(x), next(nullptr) {}
 *     ListNode(int x, ListNode *next) : val(x), next(next) {}
 * };
 */
class Solution {
public:
    ListNode* swapPairs(ListNode* head) {
        // Create a dummy node to act as the predecessor of the head.
        // This simplifies handling the head of the list.
        ListNode* dummy = new ListNode(0);
        dummy->next = head;
        
        // prevNode is the node just before the pair to be swapped.
        ListNode* prevNode = dummy;
        
        // We need at least two nodes after prevNode to perform a swap.
        while (prevNode->next != nullptr && prevNode->next->next != nullptr) {
            // Nodes to be swapped
            ListNode* firstNode = prevNode->next;
            ListNode* secondNode = prevNode->next->next;
            
            // Swapping logic
            // 1. prevNode's next should point to the second node
            prevNode->next = secondNode;
            // 2. firstNode's next should point to the node after the second node
            firstNode->next = secondNode->next;
            // 3. secondNode's next should point to the first node
            secondNode->next = firstNode;
            
            // Move prevNode for the next pair. After swapping, firstNode is the new end of the pair.
            prevNode = firstNode;
        }
        
        // The new head is dummy->next.
        ListNode* newHead = dummy->next;
        delete dummy; // Clean up the allocated dummy node
        return newHead;
    }
};

Swap Nodes in Pairs in TypeScript

/**
 * Definition for singly-linked list.
 * class ListNode {
 *     val: number
 *     next: ListNode | null
 *     constructor(val?: number, next?: ListNode | null) {
 *         this.val = (val===undefined ? 0 : val)
 *         this.next = (next===undefined ? null : next)
 *     }
 * }
 */

function swapPairs(head: ListNode | null): ListNode | null {
    // Create a dummy node to act as the predecessor of the head.
    // This simplifies handling the head of the list.
    const dummy = new ListNode(0, head);
    
    // prevNode is the node just before the pair to be swapped.
    let prevNode: ListNode = dummy;
    
    // We need at least two nodes after prevNode to perform a swap.
    while (prevNode.next !== null && prevNode.next.next !== null) {
        // Nodes to be swapped
        const firstNode = prevNode.next;
        const secondNode = prevNode.next.next;
        
        // Swapping logic
        // 1. prevNode's next should point to the second node
        prevNode.next = secondNode;
        // 2. firstNode's next should point to the node after the second node
        firstNode.next = secondNode.next;
        // 3. secondNode's next should point to the first node
        secondNode.next = firstNode;
        
        // Move prevNode for the next pair. After swapping, firstNode is the new end of the pair.
        prevNode = firstNode;
    }
    
    // The new head is dummy.next.
    return dummy.next;
};

Preparing for interviews beyond LeetCode? Practise system design, SQL and behavioral questions with an in-browser runner on KatInterview.

LeetCode is a trademark of LeetCode LLC. KatInterview is not affiliated with LeetCode.