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

# Plus One Linked List Python Solution

> Tested Python solution for LeetCode 369 with 16 pytest cases. Generate a practice environment with lcpy.

LeetCode 369, [Medium](/catalog/medium). Topics: [Linked List](/catalog/topics/linked-list), [Math](/catalog/topics/math). [View on LeetCode](https://leetcode.com/problems/plus-one-linked-list/description/).

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

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

## Problem

Given a non-negative integer represented as a linked list of digits, *plus one to the integer*.

The digits are stored such that the most significant digit is at the `head` of the list.

### Examples

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

```
Input: head = [0]
Output: [1]
```

### Constraints

* The number of nodes in the linked list is in the range `[1, 100]`.
* `0 <= Node.val <= 9`
* The number represented by the linked list does not contain leading zeros except for the zero itself.

## Solution

Reference implementation from [solution.py on GitHub](https://github.com/wislertt/leetcode-py/blob/main/leetcode/plus_one_linked_list/solution.py), full suite in [test\_solution.py](https://github.com/wislertt/leetcode-py/blob/main/leetcode/plus_one_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 plus_one(self, head: ListNode[int] | None) -> ListNode[int] | None:
        dummy = ListNode(0)
        dummy.next = head
        # rightmost node not equal to 9
        last_not_nine = dummy
        node = head
        while node is not None:
            if node.val != 9:
                last_not_nine = node
            node = node.next
        last_not_nine.val += 1
        node = last_not_nine.next
        while node is not None:
            node.val = 0
            node = node.next
        return dummy if last_not_nine is dummy else 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.