ExamAdda Logo

Swap Nodes in Pairs

Medium

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

You must swap the nodes themselves, not just their values.

If the linked list contains an odd number of nodes, the last node remains in its original position.

Example 1

Input

head = [1, 2, 3, 4]

Output

[2, 1, 4, 3]

Explanation

The first pair is swapped:

1 → 2

 

becomes:

2 → 1

 

The second pair is swapped:

3 → 4

 

becomes:

4 → 3

 

Example 2

Input

head = [1, 2, 3]

Output

head = [1, 2, 3]

Explanation

The first two nodes are swapped.

The last node has no pair, so it remains unchanged.

Constraints

0 <= number of nodes <= 100
0 <= Node.val <= 100
The linked list contains distinct or duplicate values.
Nodes must be swapped
not their values.

Hints:

Hint 1

Consider the first two nodes as a pair.

You need to change their links so that the second node comes before the first.

Hint 2

For:

1 → 2 → 3 → 4

 

first make:

2 → 1

 

and then connect 1 to the remaining list.

Author & Technical Reviewer

ExamAdda Technical Review Team

Technically reviewed by: ExamAdda Technical Review Team

Technical Reviewers, ExamAdda

Software engineers at ExamAdda who check every article's definitions, complexity claims and code examples before and after publishing.

Published

Aug 26, 2026

Last updated

Aug 26, 2026

Content Verification Methodology

Definitions and complexity claims were checked against authoritative computer-science references. Code examples were compiled and tested with standard, boundary and edge-case inputs.

Report a correction:editorial@examadda.org
Auto
Loading editor...
Input

Expected Output