โ† Amazon questions

Swap alternate elements in linked list

Filed under Amazon

Free read 2 of 3

Confirm if modifying node values is allowed or if pointer manipulation is strictly required.

The question

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

Constraints

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

Examples

Input
head = [1, 2, 3, 4]
Output
[2, 1, 4, 3]
Why
Nodes 1 and 2 are swapped, then nodes 3 and 4 are swapped.

Approach

  1. Confirm if modifying node values is allowed or if pointer manipulation is strictly required.

Solution

O(N) time, O(1) space

Python
class ListNode:
    def __init__(self, val=0, next=None):
        self.val = val
        self.next = next

def swapPairs(head):
    dummy = ListNode(0, head)
    prev, curr = dummy, head
    while curr and curr.next:
        next_pair = curr.next.next
        second = curr.next
        second.next = curr
        curr.next = next_pair
        prev.next = second
        prev = curr
        curr = next_pair
    return dummy.next

Tips

  • What they are testing: Test with empty list, single-node list, even-length list, and odd-length list.
  • Common mistake: Breaking the chain connection by losing reference to the next pair before updating pointers.

Related Amazon questions

Collected from public candidate posts and coding forums. Updated Nov 2026.