oneby7

Linked Lists Reversing and rewiring

307. Plus One Linked List

Medium

You are given head, the first node of a singly linked list that holds a non-negative integer, one decimal digit per node. The head holds the most significant digit and the last node holds the ones digit. Add one to the number and return the head of a list that holds the result in the same form.

The examples write a list as its values from the head on, so head = [4,1,6] is the list 4 → 1 → 6, which is the number 416. The output shows the list you return the same way.

Example 1

head
40799
output
40800

Input: head = [4, 0, 7, 9, 9]

Output: [4,0,8,0,0]

Explanation: The list holds 40,799, and 40,799 + 1 = 40,800. The two 9s at the end become 0s, and the 7 before them becomes 8.

Example 2

999
head
1000
output

Input: head = [9, 9, 9]

Output: [1,0,0,0]

Explanation: 999 + 1 = 1,000. The answer has one more digit than the list, so it starts with a new node holding 1.

Example 3

0
head
1
output

Input: head = [0]

Output: [1]

Explanation: The number 0 is written as [0], the only list that may start with a 0.

Check your understanding

Work out the answer for this input before you write any code.

head = [2, 9, 9]

Constraints

  • 1 ≤ number of nodes ≤ 105
  • 0 ≤ Node.val ≤ 9
  • The number has no leading zeros: the head is not 0, unless the list is just [0].

Clarifying questions

What you would ask an interviewer before writing any code.

Hints

Interview follow-ups

Runs in your browser
Code
Runs in your browser for now · some things may not work as expectedLn 1, Col 1

Article

Send feedback

Thank you for helping. We read every report and fix what is wrong.

How do you feel about oneby7?

Sign in to oneby7

Keep your progress, your streak and your code, on any device.

New here? This creates your account too.