# Plus One Linked List in C++

Suppose we have a non-negative integer represented as non-empty a singly linked list of digits, now we have to plus one to the integer. We may assume the integer do not contain any leading zero, except the number 0 itself. In the linked list the most significant digit is at the head of the list.

So, if the input is like [1,2,3], then the output will be [1,2,4]

To solve this, we will follow these steps −

• if head is null, then −

• req = NULL

• while curr is non-zero, do −

• if val of curr is not equal to 9, then −

• req := curr

• curr := next of curr

• if not req is non-zero, then −

• dummy = new node with value 1

• next of dummy := head

• while head is non-zero, do −

• val of head := 0

• return dummy

• Otherwise

• increase val of req by 1

• req := next of req

• while req is non-zero, do −

• val of req := 0

• req := next of req

## Example

Let us see the following implementation to get a better understanding.

Live Demo

#include <bits/stdc++.h>
using namespace std;
class ListNode{
public:
int val;
ListNode *next;
ListNode(int data){
val = data;
next = NULL;
}
};
ListNode *make_list(vector<int< v){
for(int i = 1; i<v.size(); i++){
while(ptr->next != NULL){
ptr = ptr->next;
}
ptr->next = new ListNode(v[i]);
}
}
cout << "[";
while(ptr){
cout << ptr->val << ", ";
ptr = ptr->next;
}
cout << "]" << endl;
}
class Solution {
public:
ListNode* req = NULL;
while (curr) {
if (curr->val != 9) {
req = curr;
}
curr = curr->next;
}
if (!req) {
ListNode* dummy = new ListNode(1);
}
return dummy;
}
else {
req->val++;
req = req->next;
while (req) {
req->val = 0;
req = req->next;
}
}
}
};
main(){
Solution ob;
vector<int< v = {1,4,5};
}

## Input

{1,4,5}

## Output

[1, 4, 6, ]

Updated on: 19-Nov-2020

139 Views