386. Swapping Nodes in a Linked List (Values)

MediumLinked ListTwo PointersLinked List

Given a linked list and an integer k, swap the values of the k-th node from the beginning and the k-th node from the end (1-indexed). Return the list as an array. Input: '[list], k'.

Input: '[list], k'.

Output: Array — the list after swapping.

Examples

Example 1
Input: [1,2,3,4,5], 2
Output: [1,4,3,2,5]
Explanation: 2nd from start (2) and 2nd from end (4) swapped.
Example 2
Input: [7,9,6,6,7,8,3,0,9,5], 5
Output: [7,9,6,6,8,7,3,0,9,5]
Explanation: 5th from each end swapped.
Example 3
Input: [1], 1
Output: [1]
Explanation: Same node.

Constraints

Asked by

AmazonOracleGoogleMicrosoftMetaBloomberg
Solve this problem in the editor →