Algorithm-Day31-Swap-Nodes-in-Pairs-lc-24

🧩 Problem Description

Given the head of a linked list, swap every two adjacent nodes and return its head.

You must solve the problem without modifying the values in the list’s nodes (i.e., only nodes themselves may be changed.)


πŸ’¬ Example

1
2
Input: head = [1,2,3,4]
Output: [2,1,4,3]

πŸ’‘ Intuition

This is a classic linked list node manipulation problem.

  • Use a dummy node to simplify edge cases.
  • Iterate through the list in pairs.
  • For each pair:
    • Update pointers to swap the two nodes.
    • Move to the next pair.

πŸ”’ Java Code (Iterative)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
class Solution {
public ListNode swapPairs(ListNode head) {
ListNode dummy = new ListNode(0);
dummy.next = head;
ListNode curr = dummy;

while (curr.next != null && curr.next.next != null) {
ListNode first = curr.next;
ListNode second = curr.next.next;

// Swapping nodes
first.next = second.next;
second.next = first;
curr.next = second;

// Move to next pair
curr = first;
}

return dummy.next;
}
}

πŸ” Java Code (Recursive)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
class Solution {
public ListNode swapPairs(ListNode head) {
if (head == null || head.next == null) return head;

ListNode first = head;
ListNode second = head.next;

first.next = swapPairs(second.next);
second.next = first;

return second;
}
}

⏱ Time and Space Complexity

  • Time Complexity: O(n), where n is the number of nodes
  • Space Complexity:
    • Iterative: O(1)
    • Recursive: O(n) due to recursion stack

✍️ Summary

  • Good test of pointer manipulation in linked lists.
  • Practice both iterative and recursive approaches.
  • Understanding node-level swaps is essential for problems like:
    • lc-25: Reverse Nodes in k-Group
    • lc-92: Reverse Linked List II

Dummy nodes make linked list problems so much easier β€” use them!