1
2
3
4
[0][1][2][3]
Shortcut · swap values
▸1given head2cur = head3while cur and cur.next:4 swap(cur.val, cur.next.val); cur = cur.next.next5return head // usually not allowed!
state
- goal2 1 4 3
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 problemGiven 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.
▸1given head2cur = head3while cur and cur.next:4 swap(cur.val, cur.next.val); cur = cur.next.next5return head // usually not allowed!
line 1Swap every adjacent pair: (1,2) then (3,4). Cheeky shortcut: leave the nodes alone and swap the VALUES inside them.