# 369.Plus-One-Linked-List

## 369. Plus One Linked List

## 题目地址

<https://leetcode.com/problems/plus-one-linked-list/>

## 题目描述

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

You may assume the integer do not contain any leading zero, except the number 0 itself.

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

Example :
Input: [1,2,3]
Output: [1,2,4]
```

## 代码

### Approach #1 Sentinel Head

Time: O(N) && Space: O(1)

```java
/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode() {}
 *     ListNode(int val) { this.val = val; }
 *     ListNode(int val, ListNode next) { this.val = val; this.next = next; }
 * }
 */
class Solution {
  public ListNode plusOne(ListNode head) {
        // sentinel head
    ListNode sentinel = new ListNode(0);
    sentinel.next = head;
    ListNode notNine = sentinel;

    // find the rightmost not-nine digit
    while (head != null) {
      if (head.val != 9)    notNine = head;
      head = head.next;
    }

    // increase thsi rightmost not-nine digit
    notNine.val++;
    notNine = notNine.next;

    while (notNine != null) {
      notNine.val = 0;
      notNine = notNie.next;
    }

    return sentinel.val != 0 ? sentinel : sentinal.next;
  }
}
```

### Approach #2 Recursive DFS

```java
class Solution {
  public ListNode plusOne(ListNode head) {
    if (DFS(head) == 0) {
      return head;
    } else {
      ListNode newHead = new ListNode(1);
      newHead.next = head;
      return newHead;
    }
  }

  private int DFS(ListNode head) {
    if (head == null)        return 1;

    if (DFS(head.next) == 0) { // carry
      return 0;
    }

    int val = head.val + 1;
    head.val = val % 10;
    return val / 10; // next carry
  }
}
```


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://wentao-shao.gitbook.io/leetcode/linked-list/369.plus-one-linked-list.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
