> ## Documentation Index
> Fetch the complete documentation index at: https://leetcode-py.wisl.dev/llms.txt
> Use this file to discover all available pages before exploring further.

> ## Agent Instructions
> leetcode-py is a Python LeetCode practice environment generator with one CLI: lcpy. It is not a service or platform.
> Each problem is a directory under leetcode/ with README.md, solution.py, test_solution.py, helpers.py, and playground.ipynb. lcpy gen creates them from JSON templates bundled with the package.
> Examples are backed by tests; copy them verbatim.

# Swapping Nodes in a Linked List

> Tested Python solution for LeetCode 1721 with 24 pytest cases. Generate a practice environment with lcpy.

LeetCode 1721, [Medium](/catalog/medium). Topics: [Linked List](/catalog/topics/linked-list), [Two Pointers](/catalog/topics/two-pointers). [View on LeetCode](https://leetcode.com/problems/swapping-nodes-in-a-linked-list/description/).

Generate this problem as a practice environment: tested reference solution, 24 [parametrized pytest cases](/practice/testing), and a playground notebook:

```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
lcpy gen -n 1721   # by problem number
lcpy gen -s swapping_nodes_in_a_linked_list   # by problem name
```

## 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](https://assets.leetcode.com/uploads/2020/09/21/linked1.jpg)

```
Input: head = [1,2,3,4,5], k = 2
Output: [1,4,3,2,5]
```

```
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]
```

### 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](https://github.com/wislertt/leetcode-py/blob/main/leetcode/swapping_nodes_in_a_linked_list/solution.py), full suite in [test\_solution.py](https://github.com/wislertt/leetcode-py/blob/main/leetcode/swapping_nodes_in_a_linked_list/test_solution.py):

```python theme={"theme":{"light":"github-light","dark":"github-dark"}}
from leetcode_py import ListNode


class Solution:
    # Time: O(n)
    # Space: O(1)
    def swap_nodes(self, head: ListNode[int] | None, k: int) -> ListNode[int] | None:
        if head is None:
            return head

        n = 1
        node = head
        while node.next is not None:
            node = node.next
            n += 1

        first = head
        for _ in range(k - 1):
            if first.next is None:
                break
            first = first.next

        second = head
        for _ in range(n - k):
            if second.next is None:
                break
            second = second.next

        first.val, second.val = second.val, first.val
        return head
```

## Complexity

| Time | Space |
| - | - |
| O(n) | O(1) |

## Tags

[NeetCode All](/catalog/neetcode).


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.