Your free access ends in 7 days — and you haven’t tried it yet. Watch one algorithm run, start to finish. It takes about two minutes.

Try one problem
0
Problem

Swap Nodes in Pairs

LeetCode #24Medium
Three arrows per pair · dummy head

Given the head of a singly linked list, swap every two adjacent nodes and return the new head. You must swap the actual nodes rather than just their values.

Asked atAmazonMicrosoftBloomberg
step 1 / 11
1
2
3
4
[0][1][2][3]
Shortcut · swap values
1given head
2cur = head
3while cur and cur.next:
4 swap(cur.val, cur.next.val); cur = cur.next.next
5return head // usually not allowed!
state
  • goal2 1 4 3

line 1Swap every adjacent pair: (1,2) then (3,4). Cheeky shortcut: leave the nodes alone and swap the VALUES inside them.