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
Inputhead = [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, 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
Inputhead = [7,9,6,6,7,8,3,0,9,5], k = 5
Output[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

Asked at 6 companies

</>

Your Solution

(Ctrl/Cmd + Enter)

Switching Language

Loading template...

Loading...

Sign in to save your progress

AI code evaluation

Get a correctness verdict, missed edge cases, and complexity analysis of your solution.

Sign in to evaluate