Search⌘ K
AI Features

Swap Nodes in Pairs

Explore how to swap every two adjacent nodes in a singly linked list while preserving their values. Understand the in-place approach to modify node connections directly, achieving an optimal O(n) time and O(1) space solution. This lesson helps you apply efficient linked list manipulation techniques necessary for coding interviews.

Statement

Given a singly linked list, swap every two adjacent nodes of the linked list. After the swap, return the head of the linked list.

Note: Solve the problem without modifying the values in the list’s nodes. In other words, only the nodes themselves can be changed.

Constraints:

  • The number of nodes in the list is in the range [0,100][0, 100].
  • 00 \leq Node.value 100\leq 100

Examples

Understand the problem

Let’s take a moment to make sure you’ve correctly understood the problem. The quiz below helps you check if you’re solving the correct problem:

Swap Nodes in Pairs

1.

Which updated linked list do we get as a result of swapping the nodes in pairs for the linked list given below?

1 → 2 → 3 → 4 → 5 → 6

A.

1 → 2 → 3 → 4 →5 → 6

B.

1 → 3 → 2 → 4 → 5 → 6

C.

2 → 1 → 4 → 3 → 6 → 5

D.

6 → 5 → 4 → 3 → 2 → 1


1 / 2

Figure it out!

We have a game for you to play. Rearrange the logical building blocks to develop a clearer understanding of how to solve this problem.

Note: As an additional challenge, we have intentionally hidden the solution to this puzzle.

Sequence - Vertical
Drag and drop the cards to rearrange them in the correct sequence.

1
2
3
4

Try it yourself

Implement your solution in main.js in the following coding playground. We have provided useful code templates in the other files that you may build on to solve this problem.

We have left the solution to this challenge as an exercise for you. The optimal solution to this problem runs in O(n) time and takes O(1) space. You may try to translate the logic of the solved puzzle into a coded solution.

JavaScript
usercode > main.js
// Definition for a Linked List node
// class ListNode {
// constructor(val = 0, next = null) {
// this.val = val;
// this.next = next;
// }
// }
import {ListNode} from './ds_v1/LinkedList.js';
function swapPairs(head){
// Replace this placeholder return statement with your code
return head;
}
export {
swapPairs
}
Swap Nodes in Pairs