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.

Auto
Loading editor...
Input

Expected Output