Given a singly linked list, swap every two adjacent nodes and return its head. You must solve the problem without modifying the values in the list's nodes; only the nodes themselves may be changed.
Function Signature
def swap_pairs(head: Optional[ListNode]) -> Optional[ListNode]:
Rules
-
Each
ListNode
has an integer field
val
and a field
next
that points to the next node, or is
None
at the tail.
-
In the examples, a list is written as its node values from head to tail.
[]
is the empty list, where
head
is
None
.
-
Pairs are taken from the head: the first and second nodes, then the third and fourth, and so on. If the list has an odd number of nodes, the last node has no partner and stays where it is.
-
Node values must not be changed. Only the
next
links may be rewired.
Constraints
-
The number of nodes in the list is in the range 0 to 100.
-
0 <= Node.val <= 100
Examples
Input: head = [1,2,3,4]
Output: [2,1,4,3]
The first pair (1, 2) becomes (2, 1) and the second pair (3, 4) becomes (4, 3), so 1 -> 2 -> 3 -> 4 becomes 2 -> 1 -> 4 -> 3.
Input: head = []
Output: []
The list is empty, so the result is also an empty list.
Input: head = [1,2,3]
Output: [2,1,3]
The pair (1, 2) is swapped. Node 3 has no partner, so it stays at the end.