Skip to content
Onsite

Swap Nodes in Pairs

MediumP2Coding

Given the head of a singly linked list, swap every two adjacent nodes and return the head of the new list. If the length is odd, the last node stays where it is. Change the pointers; do not just swap the values. A list node has val and next. The ListNode class is already defined for you.

Example 1

Input
head = [1,2,3,4]
Output
[2,1,4,3]

Example 2

Input
head = [1,2,3]
Output
[2,1,3]

Example 3

Input
head = []
Output
[]

Constraints

  • 0 <= number of nodes <= 100
  • 0 <= Node.val <= 100

Hints

Run checks the 3 visible tests, Submit all 10.