Swap Nodes in Pairs - aloalgo

Swap Nodes in Pairs

Medium

You are given a linked list.

Your task is to swap every two adjacent nodes in the linked list and return the head of the modified list.

Note that:

  • Only the node pointers should be modified; the value of the nodes must remain unchanged.

Return the head of the modified linked list.

Example 1

Input
1 → 2 → 3 → 4 → null
Output
2 → 1 → 4 → 3 → null
Explanation:

The first pair (1, 2) is swapped to (2, 1). The second pair (3, 4) is swapped to (4, 3).

Example 2

Input
None
Output
None
Explanation:

An empty list remains empty.

Example 3

Input
1 → null
Output
1 → null
Explanation:

A list with a single node remains unchanged.

Example 4

Input
1 → 2 → 3 → null
Output
2 → 1 → 3 → null
Explanation:

The pair (1, 2) is swapped to (2, 1). The last node (3) is left as is.

Loading...
Input
1 → 2 → 3 → 4 → null
Output
2 → 1 → 4 → 3 → null

Hello! I am your ✨ AI assistant. I can provide you hints, explanations, give feedback on your code, and more. Just ask me anything related to the problem you're working on!