700024. Pairwise swap elements of a linked list

Easy

Here is a detailed Markdown blog post for the problem "Pairwise swap elements of a linked list":

700024. Pairwise Swap Elements of a Linked List by Swapping Data

Summary

Given a singly linked list, pairwise swap its elements without using any extra space or recursion. This problem requires understanding and manipulation of linked lists.

Detailed Explanation

To solve this problem, we'll iterate through the linked list, swapping each pair of nodes. We can do this by keeping track of two pointers: prev and curr. prev will point to the previous node, while curr will point to the current node. We'll move prev one step ahead after processing each pair.

Here's a step-by-step breakdown:

  1. Initialize prev as NULL and curr as the head of the linked list.
  2. Traverse the linked list until curr is NULL.
  3. For each iteration:
    • Store the value of curr->next in a temporary variable, say tempNext.
    • Set curr->next to prev's value (i.e., swap the next pointer).
    • Move prev one step ahead by setting it to curr. Update curr to tempNext.
  4. Return the modified linked list.

Here's a diagram illustrating this process:

     1 -> 2 -> 3 -> 4
       ^         ^
       |         |
       prev      curr
    Swap: 1<->2, 3<->4
     2 -> 1 -> 4 -> 3

Time complexity analysis:

  • The algorithm processes each node in the linked list once, resulting in a linear time complexity of O(n), where n is the number of nodes.

Space complexity analysis:

  • We only use a constant amount of space to store the temporary variable and the two pointers, so the space complexity remains O(1).

Optimized Solutions

Java

View on GeeksforGeeks
public ListNode pairwiseSwap(ListNode head) {
    if (head == null || head.next == null) return head;

    ListNode prev = null;
    ListNode curr = head;

    while (curr != null && curr.next != null) {
        ListNode tempNext = curr.next;
        curr.next = prev;
        prev = curr;
        curr = tempNext;
    }

    return prev;
}

DevExCode

Master coding interviews with Leetcode, system design, TechBit, QuickLearn, DevTips, Tech Battles, and career services.

© 2026 DevExCode. All rights reserved.