# Plus One Linked List in C++

C++Server Side ProgrammingProgramming

#### C in Depth: The Complete C Programming Guide for Beginners

45 Lectures 4.5 hours

#### Practical C++: Learn C++ Basics Step by Step

Most Popular

50 Lectures 4.5 hours

#### Master C and Embedded C Programming- Learn as you go

66 Lectures 5.5 hours

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 −

• curr = head

• 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){
ListNode *head = new ListNode(v);
for(int i = 1; i<v.size(); i++){
ListNode *ptr = head;
while(ptr->next != NULL){
ptr = ptr->next;
}
ptr->next = new ListNode(v[i]);
}
}
ListNode *ptr = head;
cout << "[";
while(ptr){
cout << ptr->val << ", ";
ptr = ptr->next;
}
cout << "]" << endl;
}
class Solution {
public:
ListNode* plusOne(ListNode* head) {
ListNode* curr = head;
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};
ListNode *head = make_list(v);
}
{1,4,5}
[1, 4, 6, ]