AlgoMaster Logo

Swap Nodes in Pairs

Ashish

Ashish Pratap Singh

medium

Problem Description

Solve it on LeetCode

Approaches

1. Recursive Approach

The recursive approach involves swapping nodes in pairs and continues until the end of the linked list is reached. Here's the idea:

  1. Base Case: If the list is empty or has only one node, no swap is needed. Return the head.
  2. Recursive Step:
    • Swap the first two nodes.
    • Continue swapping for the rest of the list using recursion.

Code:

Iterative Approach

The iterative approach involves using a dummy node to facilitate the swapping process as we walk through the list:

  1. Setup a Dummy Node: This helps manage edge cases and makes node swapping easier.
  2. Traversal and Swapping:
    • Swap nodes by adjusting pointers.
    • Use a loop to continue swapping until the end of the list is reached.

Code: