MediumLinked ListRecursion

Swap Nodes in Pairs

LeetCode
1 approach, code in all languages

You are given the head of a singly linked list. Rearrange the list by exchanging each pair of adjacent nodes, so the first node trades places with the second, the third with the fourth, and so on.

If the list contains an odd number of nodes, the final leftover node keeps its position. You are not allowed to change the values stored inside the nodes; the swap must be performed purely by relinking the next pointers. Return the head of the modified list.

Example 1

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

Output: [2,1,4,3]

The pair (1,2) becomes (2,1) and the pair (3,4) becomes (4,3).

Example 2

Input: head = [1,2,3]

Output: [2,1,3]

The first two nodes swap, while the lone trailing node 3 has no partner and stays where it is.

Constraints

  • The number of nodes in the list is in the range [0, 100].
  • 0 <= Node.val <= 100
You've got the patterns

Patterns get you through the screen. Shipping gets you hired.

FDE Coach is a cohort-based program in frontend, backend, AWS, and AI where you build real products and get referred to 200+ hiring partners. The free live workshop is the fastest way to see how we teach.

750+ engineers trained · frontend, backend, AWS & AI

August 15 · 0d left
Enroll Now