Skip to main content
Back to problems
Leetcode
Medium
Linked Lists
Two Pointers
Amazon
Swapping Nodes In A Linked List

Swap the values of the kk-th node from the beginning and the kk-th node from the end of a singly linked list.

Acceptance 0%
Problem Statement

Swapping Nodes in a Linked List

You are given the head of a singly linked list and an integer kk.

Swap the values stored in the kk-th node from the start and the kk-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 kk-th node from the end means the node that is kk positions from the tail when counting from 1.
  • You may assume 1kn1 \le k \le n, where nn is the length of the list.

Input Format

  • The first line contains the linked list values in order.
  • The second line contains an integer kk.

For backend ingestion, treat the input as:

  • head: the head node of a singly linked list
  • k: 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.
  • 1kn1 \le k \le n
  • Only node values are swapped; links are not modified.
  • Aim for O(n)O(n) time and O(1)O(1) extra space if possible.
Examples
Sample cases returned by the problem API.

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.

Guided hints
Editorial and discussion links
Concept map and variants
Sign in to unlock
Track your progress
Sign in to bookmark this problem, save notes, and manage its revision plan.