Search⌘ K
AI Features

Swapping Nodes in a Linked List

Swapping Nodes in a Linked List asks you to exchange the values of the kth node from the beginning and the kth node from the end, then return the updated list.

Statement

Given the head of a linked list and an integer, k, return the head of the linked list after swapping the values of the kthk^{th} node from the beginning and the kthk^{th} node from the end of the linked list.

Note: We’ll number the nodes of the linked list starting from 11 to nn.

Constraints:

  • The linked list will have n number of nodes.
  • 1≤1 \leq k ≤\leq n ≤500\leq 500
  • −5000≤-5000 \leq Node.Value ≤5000\leq 5000

Examples

Understand the problem

Let’s take a moment to make sure you’ve correctly understood the problem. The quiz below helps you check if you’re solving the correct problem:

Technical Quiz
1.

What is the output if the following data is given as input?

linked list = 4 → 2 → 7 → 8 → 9 → 0 → 2

k = 3

A.

8 → 9 → 0 → 4 → 2 → 7 → 2

B.

7 → 2 → 4 → 0 → 9 → 8 → 2

C.

4 → 2 → 9 → 8 → 7 → 0 → 2

D.

2 → 9 → 0 → 4 → 2 → 7 → 8


1 / 4

Figure it out!

We have a game for you to play. Rearrange the logical building blocks to develop a clearer understanding of how to solve this problem.

Sequence - Vertical
Drag and drop the cards to rearrange them in the correct sequence.

1
2
3
4
5
6

Try it yourself

Implement your solution in the following coding playground.

Go
usercode > Solution.go
// Definition for a Linked List node
// type ListNode struct {
// Val int
// Next *ListNode
// }
package main
import (. "golang-test-code/ds_v1/LinkedList")
func swapNodes(head *ListNode, k int) *ListNode {
// Replace this placeholder return statement with your code
return new(ListNode)
}
Swapping Nodes in a Linked List