You are given the head of a singly linked list and an integer k. Swap the values of the kth node from the beginning and the kth node from the end of the list, then return the head of the list. Positions are 1-indexed.
Function Signature
def swap_nodes(head: Optional[ListNode], k: int) -> Optional[ListNode]:
Rules
-
Each node has an integer field
val
and a field
next
that points to the following node (
None
at the tail).
-
In the examples a linked list is written as the list of its values from head to tail. The output is the list after the swap, written the same way.
-
Only the two values change places. The nodes keep their order, so the returned head is the original head node.
-
When both positions refer to the same node (the middle node of an odd-length list), the list stays as it was.
Constraints
-
The number of nodes in the list is
n
.
-
1 <= k <= n <= 10^5
-
0 <= Node.val <= 100
Examples
Input: head = [1,2,3,4,5], k = 2
Output: [1,4,3,2,5]
The 2nd node from the beginning has value 2 and the 2nd node from the end has value 4. Swapping those two values gives [1,4,3,2,5].
Input: head = [7,9,6,6,7,8,3,0,9,5], k = 5
Output: [7,9,6,6,8,7,3,0,9,5]
The list has 10 nodes. The 5th node from the beginning holds 7 and the 5th node from the end (the 6th from the beginning) holds 8, so those two values trade places.
Input: head = [1,2,3], k = 2
Output: [1,2,3]
The 2nd node from the beginning and the 2nd node from the end are both the middle node, so nothing changes.