ExamAdda Logo

Swap Nodes in Pairs

Medium

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

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

Return the head of the modified linked list.

Example 1

Input

n = 4
head = [1, 2, 3, 4]

Output

[2, 1, 4, 3]

Explanation

The first pair [1, 2] becomes [2, 1].

The second pair [3, 4] becomes [4, 3].

Therefore, the resulting list is [2, 1, 4, 3].

Example 2

Input

n = 3
head = [1, 2, 3]

Output

[2, 1, 3]

Explanation

The first two nodes are swapped.

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

Constraints

0 <= n <= 100
0 <= Node.val <= 100
Nodes must be swapped by changing links.
Do not swap only the values.

Hints:

Hint 1

Consider the linked list as pairs:

1 → 2 → 3 → 4

 

Swap the first two nodes, then recursively or iteratively process the remaining list.

Hint 2

For every pair:

first → second → remaining

 

Change the links so that:

second → first → remaining

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