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).

30:00

Swapping Nodes in a Linked List
medium
Free written solution
Topics
Companies

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 nn.

  • 1≤k≤n≤1051 \leq k \leq n \leq 10^5

  • 0≤Node.val≤1000 \leq \text{Node.val} \leq 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
→null1234512345

k-th from front

-

k-th from end

not known yet

Variables
VariableValue
k2
DepthFunction Call
Stack empty
0/17