/24. Swap Nodes in Pairs

24. Swap Nodes in Pairs

Medium
Linked Lists69.1% acceptance

Given the head node of a singly linked list, swap every two adjacent nodes and return the head node of the modified list. You must not modify the values of the nodes; only the node connections may be changed.

Example 1

Input: [5, 7, 9, 11]

Output: [7, 5, 11, 9]

Explanation: Nodes 5 and 7 are swapped, nodes 9 and 11 are swapped.

Example 2

Input: []

Output: []

Explanation: Empty list remains unchanged.

Example 3

Input: [8]

Output: [8]

Explanation: Single node list remains unchanged.

Example 4

Input: [3, 4, 5]

Output: [4, 3, 5]

Explanation: Nodes 3 and 4 are swapped, node 5 remains.

Constraints

  • 0 <= number of nodes in the list <= 100
  • 0 <= node value <= 100
Python (current runtime)

Case 1

Input: [10, 20, 30, 40, 50, 60]

Expected: [20, 10, 40, 30, 60, 50]

Case 2

Input: [1, 2]

Expected: [2, 1]

Case 3

Input: [99, 100, 101]

Expected: [100, 99, 101]

Case 4

Input: [42]

Expected: [42]