Swap the values of the -th node from the beginning and the -th node from the end of a singly linked list.
Swapping Nodes in a Linked List
You are given the head of a singly linked list and an integer .
Swap the values stored in the -th node from the start and the -th node from the end of the list. The list structure itself should remain unchanged; only node values are swapped.
Return the head of the modified list.
Notes
- The list is 1-indexed.
- The -th node from the end means the node that is positions from the tail when counting from 1.
- You may assume , where is the length of the list.
Input Format
- The first line contains the linked list values in order.
- The second line contains an integer .
For backend ingestion, treat the input as:
head: the head node of a singly linked listk: an integer
Output Format
Return the head of the linked list after swapping the two node values.
Constraints
- The list contains at least one node.
- Only node values are swapped; links are not modified.
- Aim for time and extra space if possible.
Example 1
Input
head = [1,2,3,4,5], k = 2
Output
[1,4,3,2,5]
Explanation
The 2nd node from the start has value 2, and the 2nd node from the end has value 4. Swapping them gives [1,4,3,2,5].
Example 2
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]
Explanation
The 5th node from the start has value 7, and the 5th node from the end has value 8. After swapping values, the list is updated accordingly.
Premium problem context
Unlock deeper context for this problem
Premium adds guided hints, editorial links, similar variants, discussion resources, and concept maps so you can understand why a problem matters, not just solve it once.