Swap alternate elements in linked list
Filed under Amazon
Free read 2 of 3Confirm 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
Confirm if modifying node values is allowed or if pointer manipulation is strictly required.
Extract values into an array, swap adjacent values in the array, and write them back to the linked list nodes.
Use an iterative approach with a dummy head pointer. Maintain pointers for the previous node and the current pair, adjusting three pointers per swap operation.
List with 0 or 1 element where no swaps should occur.
Solution
O(N) time, O(1) space
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.