</>Ali · LeetCode
#0024·MediumLinked Lists

Swap Nodes in Pairs

LeetCode #24 · Medium · Linked Lists · C++ solution with worked-out approach and complexity analysis.

Approach

Iterative Pointer Swapping

Key insight

We can swap each pair in place by rewiring three pointers per pair: the previous pair's tail, the current pair's two nodes, and the next pair's head. The new head is simply the second node of the first pair.

Strategy

  1. 1Handle base cases: empty list or single node.
  2. 2Save the new head (head->next) since it becomes the final return value.
  3. 3Track `prev` (tail of the previously swapped pair), `left` and `right`
  4. 4For each pair, save `temp = right->next`, then point right->left and
  5. 5Advance: prev = left, left = temp, right = temp->next. Stop when fewer
Time
O(n)
each node is visited once.
Space
O(1)
only a constant number of pointers are used.
Problem description(from LeetCode)

Given 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).

Examples

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

Constraints

  • The number of nodes in the list is in the range [0, 100].
  • 0 <= Node.val <= 100

C++ Solution

solution.cpp
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) {
    if (head == nullptr || head->next == nullptr) return head;

    ListNode *newHead = head->next;
    ListNode *prev = nullptr;
    ListNode *left = head;
    ListNode *right = head->next;

    while (true) {
      ListNode *temp = right->next;

      right->next = left;
      left->next = temp;

      if (prev != nullptr) prev->next = right;
      if (temp == nullptr || temp->next == nullptr) return newHead;

      prev = left;
      left = temp;
      right = temp->next;
    }

    return newHead;
  }
};