Skip to interview prep
Apexed

82. Swap Nodes in Pairs

MediumLinked lists

Swap every two adjacent nodes of a linked list and return the new head. A final unpaired node stays where it is. Relink the nodes instead of changing their values.

A linked list is passed as ListNode objects with val and next. The tests write lists as arrays.

Example 1

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

Constraints

  • 0 ≤ nodes ≤ 100

Tab indents · Ctrl/⌘ + Enter runs · Esc then Tab leaves the editor

Run checks these cases; the expected output comes from the reference solution. Submit judges all 4 hidden and sample tests.

Code runs only in your browser in an isolated sandbox. Progress and submissions are saved on this device.

Swap Nodes in Pairs — coding interview practice — Apexed