Swap Nodes In Pairs

Medium Topics Company Tags

Swap the first two nodes of the singly linked list, then the next two nodes, and continue pair by pair. Return the new head. If the list has an odd number of nodes, leave the final node in place. Change the links between nodes rather than changing the values stored in them. Arrays in the examples and test inputs show node values from head to tail; [] represents an empty list.

Example 1:

Swap Nodes in Pairs, example 1: illustration of the example

Input: head = [4,7,2,9]

Output: [7,4,9,2]

Explanation: Swap the nodes containing 4 and 7, then swap the nodes containing 2 and 9. The resulting chain is 7 -> 4 -> 9 -> 2.

Example 2:

Swap Nodes in Pairs, example 2: illustration of the example

Input: head = [8,3,5]

Output: [3,8,5]

Explanation: Swap the first pair, containing 8 and 3. The final node containing 5 has no partner and stays at the end.

Example 3:

Swap Nodes in Pairs, example 3: illustration of the example

Input: head = []

Output: []

Explanation: An empty list has no pairs to swap, so return an empty list.

Constraints:

  • The list contains between 0 and 100 nodes.
  • 0 <= Node.val <= 100
  • Swap nodes by changing links; do not modify node values.


Topics

Company Tags

Please upgrade to NeetCode Pro to view company tags.