Skip to main content
LeetCode 1721, Medium. Topics: Linked List, Two Pointers. View on LeetCode. Generate this problem as a practice environment: tested reference solution, 24 parametrized pytest cases, and a playground notebook:

Problem

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<sup>th</sup> node from the beginning and the k<sup>th</sup> node from the end (the list is 1-indexed).

Examples

Example 1

Constraints

  • The number of nodes in the list is n.
  • 1 <= k <= n <= 10^5
  • 0 <= Node.val <= 100
Follow up: Could you do this in one pass?

Solution

Reference implementation from solution.py on GitHub, full suite in test_solution.py:

Complexity

Tags

NeetCode All.
Last modified on September 7, 2026