464. Plus One Linked List

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.

Example 1:

Input: head = [1,2,3]

Output: [1,2,4]

Explaination : The linked list represents the number 123. Adding one to it results in 124. We traverse to the last node, increment its value by one, and since it does not become 10, no carry propagation is needed. Thus, the final linked list is [1,2,4].

Example 2:

Input: head = [0]

Output: [1]

Explaination: The linked list represents the number 0. Adding one results in 1. We simply update the node’s value from 0 to 1, and since there are no other digits, the final linked list is [1].

Now Your Turn!

Pick the correct output for the given input

Input : head = [1,5,9]

Still unsure what the problem is asking ?

Let’s go through a few more examples, step by step, to make it clearer.

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. 

Hints

Frequently Occurring Doubts

Interview Follow-up Questions

0
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode() : val(0), next(nullptr) {}
* ListNode(int x) : val(x), next(nullptr) {}
* ListNode(int x, ListNode *next) : val(x), next(next) {}
* };
*/
class Solution {
public:
ListNode* plusOne(ListNode* head) {
// Your code goes here
}
};
Test Case

Input:

Head