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).
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:
Input: {"head":[1,2,3,4,5],"k":2}
Output: [1,4,3,2,5]
Constraints:
The number of nodes in the list is n.
1≤k≤n≤105
0≤Node.val≤100
Test Cases
Input (Stdin)
Expected Output (Stdout)
Execution Result
Run code to see results.
Input
arr ={"head":[1,2,3,4,5],"k":2}
The list has 5 nodes and k = 2. Swap the values of node 2 from the front and node 2 from the end. A singly linked list cannot walk backwards, so use two pointers with a fixed gap.
1. front walks k - 1 = 12. slide the gap to the tail3. swap values