/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 of the modified list. You must not modify the values of the nodes; only the node connections may be changed.

Example 1

Input: ListNode(5, ListNode(7, ListNode(9, ListNode(11))))

Output: [7,5,11,9]

Explanation: Pairs (5,7) and (9,11) are swapped.

Example 2

Input: ListNode(42)

Output: [42]

Explanation: Single node, no swap.

Example 3

Input: None

Output: []

Explanation: Empty list, no nodes.

Example 4

Input: ListNode(8, ListNode(6, ListNode(4)))

Output: [6,8,4]

Explanation: First pair (8,6) swapped, last node (4) remains.

Constraints

  • 0 <= number of nodes <= 100
  • 0 <= node value <= 100
  • Input is a singly linked list
  • You must not modify node values, only node connections
Python (current runtime)

Case 1

Input: ListNode(10, ListNode(20, ListNode(30, ListNode(40, ListNode(50)))))

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

Case 2

Input: ListNode(3, ListNode(1))

Expected: [1,3]

Case 3

Input: ListNode(99, ListNode(100))

Expected: [100,99]

Case 4

Input: ListNode(15, ListNode(25, ListNode(35)))

Expected: [25,15,35]