
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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 −
return head
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
head := next of head
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
return head
Example
Let us see the following implementation to get a better understanding.
#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[0]); for(int i = 1; i<v.size(); i++){ ListNode *ptr = head; while(ptr->next != NULL){ ptr = ptr->next; } ptr->next = new ListNode(v[i]); } return head; } void print_list(ListNode *head){ ListNode *ptr = head; cout << "["; while(ptr){ cout << ptr->val << ", "; ptr = ptr->next; } cout << "]" << endl; } class Solution { public: ListNode* plusOne(ListNode* head) { if (!head) return 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); dummy->next = head; while (head) { head->val = 0; head = head->next; } return dummy; } else { req->val++; req = req->next; while (req) { req->val = 0; req = req->next; } return head; } } }; main(){ Solution ob; vector<int< v = {1,4,5}; ListNode *head = make_list(v); print_list(ob.plusOne(head)); }
Input
{1,4,5}
Output
[1, 4, 6, ]