linked-list
pointers
recursion

Given the head of a singly linked list, swap every two adjacent nodes and return the head of the modified list. You must solve it by only changing node links (not the values stored inside the nodes).

Input / output

  • Input: head: ListNode (JSON test fixture is a plain array of node values, e.g. [1, 2, 3, 4] means 1 -> 2 -> 3 -> 4 -> null)
  • Output: ListNode (serialized the same way)

Constraints

  • The number of nodes in the list is between 0 and 100.
  • 0 <= node value <= 100

Follow-up

Can you solve it both iteratively (with a dummy head and a prev pointer) and recursively, and explain why the recursive version costs O(n) call-stack space that the iterative version avoids?

Examples

Example 1

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

Example 2 (empty list)

Input: head = []
Output: []

Example 3 (single node)

Input: head = [1]
Output: [1]
🔒 6 hidden

Running will execute all 9 cases, including 6 hidden ones.