Swapping Nodes in a Linked List
You are given the head of a linked list, and an integer k.
Return the head of the linked list after swapping the values of the k^th node from the beginning and the k^th node from the end. The list is 1-indexed.
Example 1
[1] -> [2] -> [3] -> [4] -> [5] -> null --- [1] -> [4] -> [3] -> [2] -> [5] -> null
Input
head = [1,2,3,4,5], k = 2Output
[1,4,3,2,5]The 2nd node from the beginning has value 2, and the 2nd node from the end has value 4, so their values are swapped.
Example 2
[7] -> [9] -> [6] -> [6] -> [7] -> [8] -> [3] -> [0] -> [9] -> [5] -> null --- [7] -> [9] -> [6] -> [6] -> [8] -> [7] -> [3] -> [0] -> [9] -> [5] -> null
Input
head = [7,9,6,6,7,8,3,0,9,5], k = 5Output
[7,9,6,6,8,7,3,0,9,5]The 5th node from the beginning has value 7, and the 5th node from the end has value 8, so their values are swapped.
Constraints
- The number of nodes in the list is
n. - 1 <= k <= n <= 10^5
- 0 <= Node.val <= 100