[Expected Approach - 1] Using Recursive Method - O(n) Time and O(n) Space:
The idea is to recursively traverse the linked list, reaching the last node first. This ensures that the least significant digit is processed before others. Add 1 to the value of the last node and compute any carry resulting from this addition. While backtracking, update each node's value based on the carry propagated from the subsequent node. After traversing, if the carry is not equals to 0, create new node with the data as carry andinsert it at head.
Below is the implementation of above approach.
C++
// C++ program to add one to a linked list#include<iostream>usingnamespacestd;classNode{public:intdata;Node*next;Node(intx){data=x;next=nullptr;}};// Recursively add 1 from end to beginning and return// carry after all nodes are processed.intaddWithCarry(Node*head){// If linked list is empty, return carryif(head==nullptr){return1;}// Add carry returned by the next node callintres=head->data+addWithCarry(head->next);// Update data and return new carryhead->data=res%10;returnres/10;}Node*addOne(Node*head){// Add 1 to linked list from end to beginningintcarry=addWithCarry(head);// If there is carry after updating all nodes,// then we need to add a new node to the linked listif(carry){Node*newNode=newNode(carry);newNode->next=head;// New node becomes head nowreturnnewNode;}returnhead;}voidprintList(Node*head){Node*curr=head;while(curr!=nullptr){cout<<curr->data<<" ";curr=curr->next;}cout<<endl;}intmain(){// Create a hard-coded linked list:// 1 -> 9 -> 9 -> 9Node*head=newNode(1);head->next=newNode(9);head->next->next=newNode(9);head->next->next->next=newNode(9);head=addOne(head);printList(head);return0;}
C
// C program to add one to a linked list#include<stdio.h>#include<stdlib.h>structNode{intdata;structNode*next;};structNode*createNode(intdata);// Recursively add 1 from end to beginning and return// carry after all nodes are processed.intaddWithCarry(structNode*head){// If linked list is empty, return carryif(head==NULL){return1;}// Add carry returned by the next node callintres=head->data+addWithCarry(head->next);// Update data and return new carryhead->data=res%10;returnres/10;}structNode*addOne(structNode*head){// Add 1 to linked list from end to beginningintcarry=addWithCarry(head);// If there is carry after updating all nodes,// then we need to add a new node to the linked listif(carry){structNode*newNode=createNode(carry);newNode->next=head;// New node becomes head nowreturnnewNode;}returnhead;}voidprintList(structNode*head){structNode*curr=head;while(curr!=NULL){printf("%d ",curr->data);curr=curr->next;}printf("\n");}structNode*createNode(intdata){structNode*newNode=(structNode*)malloc(sizeof(structNode));newNode->data=data;newNode->next=NULL;returnnewNode;}intmain(){// Create a hard-coded linked list:// 1 -> 9 -> 9 -> 9structNode*head=createNode(1);head->next=createNode(9);head->next->next=createNode(9);head->next->next->next=createNode(9);head=addOne(head);printList(head);return0;}
Java
// Java program to add one to a linked listclassNode{intdata;Nodenext;Node(intdata){this.data=data;this.next=null;}}// Recursively add 1 from end to beginning and return// carry after all nodes are processed.classGfG{staticintaddWithCarry(Nodehead){// If linked list is empty, return carryif(head==null){return1;}// Add carry returned by the next node callintres=head.data+addWithCarry(head.next);// Update data and return new carryhead.data=res%10;returnres/10;}staticNodeaddOne(Nodehead){// Add 1 to linked list from end to beginningintcarry=addWithCarry(head);// If there is carry after updating all nodes,// then we need to add a new node to the linked listif(carry>0){NodenewNode=newNode(carry);newNode.next=head;// New node becomes head nowreturnnewNode;}returnhead;}staticvoidprintList(Nodehead){Nodecurr=head;while(curr!=null){System.out.print(curr.data+" ");curr=curr.next;}System.out.println();}publicstaticvoidmain(String[]args){// Create a hard-coded linked list:// 1 -> 9 -> 9 -> 9Nodehead=newNode(1);head.next=newNode(9);head.next.next=newNode(9);head.next.next.next=newNode(9);head=addOne(head);printList(head);}}
Python
# Python program to add one to a linked listclassNode:def__init__(self,data):self.data=dataself.next=None# Recursively add 1 from end to beginning and return# carry after all nodes are processed.defaddWithCarry(head):# If linked list is empty, return carryifheadisNone:return1# Add carry returned by the next node callres=head.data+addWithCarry(head.next)# Update data and return new carryhead.data=res%10returnres//10defaddOne(head):# Add 1 to linked list from end to beginningcarry=addWithCarry(head)# If there is carry after updating all nodes,# then we need to add a new node to the linked listifcarry:newNode=Node(carry)newNode.next=head# New node becomes head nowreturnnewNodereturnheaddefprintList(head):curr=headwhilecurr:print(curr.data,end=" ")curr=curr.nextprint()if__name__=="__main__":# Create a hard-coded linked list:# 1 -> 9 -> 9 -> 9head=Node(1)head.next=Node(9)head.next.next=Node(9)head.next.next.next=Node(9)head=addOne(head)printList(head)
C#
// C# program to add 1 to a linked list usingSystem;classNode{publicintdata;publicNodenext;publicNode(intdata){this.data=data;this.next=null;}}classGfG{// Recursively add 1 from end to beginning and return// carry after all nodes are processed.staticintaddWithCarry(Nodehead){// If linked list is empty, return carryif(head==null){return1;}// Add carry returned by the next node callintres=head.data+addWithCarry(head.next);// Update data and return new carryhead.data=res%10;returnres/10;}staticNodeaddOne(Nodehead){// Add 1 to linked list from end to beginningintcarry=addWithCarry(head);// If there is carry after updating all nodes,// then we need to add a new node to the linked listif(carry>0){NodenewNode=newNode(carry);newNode.next=head;// New node becomes head nowreturnnewNode;}returnhead;}staticvoidprintList(Nodehead){Nodecurr=head;while(curr!=null){Console.Write(curr.data+" ");curr=curr.next;}Console.WriteLine();}staticvoidMain(){// Create a hard-coded linked list:// 1 -> 9 -> 9 -> 9Nodehead=newNode(1);head.next=newNode(9);head.next.next=newNode(9);head.next.next.next=newNode(9);head=addOne(head);printList(head);}}
JavaScript
// Javascript program to add one to a linked listclassNode{constructor(data){this.data=data;this.next=null;}}// Recursively add 1 from end to beginning and return// carry after all nodes are processed.functionaddWithCarry(head){// If linked list is empty, return carryif(head===null){return1;}// Add carry returned by the next node callconstres=head.data+addWithCarry(head.next);// Update data and return new carryhead.data=res%10;returnMath.floor(res/10);}functionaddOne(head){// Add 1 to linked list from end to beginningconstcarry=addWithCarry(head);// If there is carry after updating all nodes,// then we need to add a new node to the linked listif(carry>0){constnewNode=newNode(carry);newNode.next=head;// New node becomes head nowreturnnewNode;}returnhead;}functionprintList(head){letcurr=head;while(curr!==null){console.log(curr.data+" ");curr=curr.next;}console.log();}// Create a hard-coded linked list:// 1 -> 9 -> 9 -> 9lethead=newNode(1);head.next=newNode(9);head.next.next=newNode(9);head.next.next.next=newNode(9);head=addOne(head);printList(head);
Output
2 0 0 0
Time Complexity: O(n), where n is the number of nodes in the linked list. Auxiliary Space: O(n)
[Expected Approach - 2] Using Iterative Method - O(n) Time and O(1) Space:
The idea is to start by reversing the entire linked list. This allows you to begin processing the digits from the least significant to the most significant. Add 1 to the value of this head node. If this addition results in a carry (i.e., the new value exceeds 9), update the current node to store only the last digit (value modulo 10) and pass the carry to the next node. Continue traversing subsequent nodes until we reach the end of the list or the carry becomes 0. Reverse the linked list again to restore it to itsoriginal order.
Below is the implementation of above approach.
C++
// C++ program to add one to a linked list#include<bits/stdc++.h>usingnamespacestd;classNode{public:intdata;Node*next;Node(intx){data=x;next=nullptr;}};// Function to reverse the linked listNode*reverse(Node*head){Node*curr=head,*prev=nullptr,*next;while(curr!=nullptr){next=curr->next;curr->next=prev;prev=curr;curr=next;}returnprev;}// Function to add one to a linked list and // return the head node of the resultant listNode*addOneUtil(Node*head){Node*res=head;Node*curr=head;Node*last=nullptr;// Initialize carry with 1 (to add one)intcarry=1;intsum;while(curr!=nullptr){// Calculate sum of carry and current node's datasum=carry+curr->data;// Update carry for next digitcarry=(sum>=10)?1:0;// Update current node's data to sum modulo 10curr->data=sum%10;// Move to the next nodelast=curr;curr=curr->next;}// If there's a carry left, add a // new node with carry valueif(carry>0){last->next=newNode(carry);}returnres;}// Main function to add one to the linked listNode*addOne(Node*head){// Reverse the linked listhead=reverse(head);// Add one to the reversed listhead=addOneUtil(head);// Reverse the list again to restore// the original orderreturnreverse(head);}voidprintList(Node*head){Node*curr=head;while(curr!=nullptr){cout<<curr->data<<" ";curr=curr->next;}cout<<endl;}intmain(){// Create a hard-coded linked list:// 1 -> 9 -> 9 -> 9Node*head=newNode(1);head->next=newNode(9);head->next->next=newNode(9);head->next->next->next=newNode(9);head=addOne(head);printList(head);return0;}
C
// C program to add 1 to a linked list#include<stdio.h>#include<stdlib.h>structNode{intdata;structNode*next;};structNode*createNode(intdata);// Function to reverse the linked liststructNode*reverse(structNode*head){structNode*curr=head;structNode*prev=NULL;structNode*next;while(curr!=NULL){next=curr->next;curr->next=prev;prev=curr;curr=next;}returnprev;}// Function to add one to a linked list and // return the head node of the resultant liststructNode*addOneUtil(structNode*head){structNode*res=head;structNode*curr=head;structNode*last=NULL;// Initialize carry with 1 (to add one)intcarry=1;intsum;while(curr!=NULL){// Calculate sum of carry and current node's datasum=carry+curr->data;// Update carry for next digitcarry=(sum>=10)?1:0;// Update current node's data to sum modulo 10curr->data=sum%10;// Move to the next nodelast=curr;curr=curr->next;}// If there's a carry left, add a new// node with carry valueif(carry>0){last->next=createNode(carry);}returnres;}// Main function to add one to the linked liststructNode*addOne(structNode*head){// Reverse the linked listhead=reverse(head);// Add one to the reversed listhead=addOneUtil(head);// Reverse the list again to restore // the original orderreturnreverse(head);}voidprintList(structNode*head){structNode*curr=head;while(curr!=NULL){printf("%d ",curr->data);curr=curr->next;}printf("\n");}structNode*createNode(intdata){structNode*newNode=(structNode*)malloc(sizeof(structNode));newNode->data=data;newNode->next=NULL;returnnewNode;}intmain(){// Create a hard-coded linked list:// 1 -> 9 -> 9 -> 9structNode*head=createNode(1);head->next=createNode(9);head->next->next=createNode(9);head->next->next->next=createNode(9);head=addOne(head);printList(head);return0;}
Java
// Java program to add 1 to a linked listclassNode{intdata;Nodenext;Node(intx){this.data=x;this.next=null;}}// Function to reverse the linked listclassGfG{staticNodereverse(Nodehead){Nodecurr=head,prev=null,next;while(curr!=null){next=curr.next;curr.next=prev;prev=curr;curr=next;}returnprev;}// Function to add one to a linked list and // return the head node of the resultant liststaticNodeaddOneUtil(Nodehead){Noderes=head;Nodecurr=head;Nodelast=null;// Initialize carry with 1 (to add one)intcarry=1;intsum;while(curr!=null){// Calculate sum of carry // and current node's datasum=carry+curr.data;// Update carry for next digitcarry=(sum>=10)?1:0;// Update current node's data to sum modulo 10curr.data=sum%10;// Move to the next nodelast=curr;curr=curr.next;}// If there's a carry left, add a new// node with carry valueif(carry>0){last.next=newNode(carry);}returnres;}// Main function to add one to the linked liststaticNodeaddOne(Nodehead){// Reverse the linked listhead=reverse(head);// Add one to the reversed listhead=addOneUtil(head);// Reverse the list again to restore//the original orderreturnreverse(head);}staticvoidprintList(Nodehead){Nodecurr=head;while(curr!=null){System.out.print(curr.data+" ");curr=curr.next;}System.out.println();}publicstaticvoidmain(String[]args){// Create a hard-coded linked list:// 1 -> 9 -> 9 -> 9Nodehead=newNode(1);head.next=newNode(9);head.next.next=newNode(9);head.next.next.next=newNode(9);head=addOne(head);printList(head);}}
Python
# Python3 program to add 1 to a linked listclassNode:def__init__(self,data):self.data=dataself.next=None# Function to reverse the linked listdefreverse(head):curr=headprev=Nonewhilecurr:next=curr.nextcurr.next=prevprev=currcurr=nextreturnprev# Function to add one to a linked list and# return the head node of the resultant listdefaddOneUtil(head):res=headcurr=headlast=None# Initialize carry with 1 (to add one)carry=1whilecurr:# Calculate sum of carry and current node's datasum=carry+curr.data# Update carry for next digitcarry=1ifsum>=10else0# Update current node's data to sum modulo 10curr.data=sum%10# Move to the next nodelast=currcurr=curr.next# If there's a carry left, add a new# node with carry valueifcarry>0:last.next=Node(carry)returnres# Main function to add one to the linked listdefaddOne(head):# Reverse the linked listhead=reverse(head)# Add one to the reversed listhead=addOneUtil(head)# Reverse the list again to restore# the original orderreturnreverse(head)defprintList(head):curr=headwhilecurr:print(curr.data,end=" ")curr=curr.nextprint()if__name__=='__main__':# Create a hard-coded linked list:# 1 -> 9 -> 9 -> 9head=Node(1)head.next=Node(9)head.next.next=Node(9)head.next.next.next=Node(9)head=addOne(head)printList(head)
C#
// C# program to add 1 to a linked listusingSystem;classNode{publicintdata;publicNodenext;publicNode(intx){this.data=x;this.next=null;}}classGfG{// Function to reverse the linked liststaticNodeReverse(Nodehead){Nodecurr=head,prev=null,next=null;while(curr!=null){next=curr.next;curr.next=prev;prev=curr;curr=next;}returnprev;}// Function to add one to a linked list and // return the head node of the resultant liststaticNodeAddOneUtil(Nodehead){Noderes=head;Nodecurr=head;Nodelast=null;// Initialize carry with 1 (to add one)intcarry=1;intsum;while(curr!=null){// Calculate sum of carry and // current node's datasum=carry+curr.data;// Update carry for next digitcarry=(sum>=10)?1:0;// Update current node's data to sum modulo 10curr.data=sum%10;// Move to the next nodelast=curr;curr=curr.next;}// If there's a carry left, add a new // node with carry valueif(carry>0){last.next=newNode(carry);}returnres;}// Main function to add one to the linked liststaticNodeAddOne(Nodehead){// Reverse the linked listhead=Reverse(head);// Add one to the reversed listhead=AddOneUtil(head);// Reverse the list again to restore// the original orderreturnReverse(head);}staticvoidPrintList(Nodehead){Nodecurr=head;while(curr!=null){Console.Write(curr.data+" ");curr=curr.next;}Console.WriteLine();}staticvoidMain(){// Create a hard-coded linked list:// 1 -> 9 -> 9 -> 9Nodehead=newNode(1);head.next=newNode(9);head.next.next=newNode(9);head.next.next.next=newNode(9);head=AddOne(head);PrintList(head);}}
JavaScript
// Javascript program to add 1 to a linked list classNode{constructor(data){this.data=data;this.next=null;}}// Function to reverse the linked listfunctionreverse(head){letcurr=head,prev=null,next;while(curr!=null){next=curr.next;curr.next=prev;prev=curr;curr=next;}returnprev;}// Function to add one to a linked list and // return the head node of the resultant listfunctionaddOneUtil(head){letres=head;letcurr=head;letlast=null;// Initialize carry with 1 (to add one)letcarry=1;letsum;while(curr!=null){// Calculate sum of carry and current node's datasum=carry+curr.data;// Update carry for next digitcarry=(sum>=10)?1:0;// Update current node's data to sum modulo 10curr.data=sum%10;// Move to the next nodelast=curr;curr=curr.next;}// If there's a carry left, add a new// node with carry valueif(carry>0){last.next=newNode(carry);}returnres;}// Main function to add one to the linked listfunctionaddOne(head){// Reverse the linked listhead=reverse(head);// Add one to the reversed listhead=addOneUtil(head);// Reverse the list again to restore// the original orderreturnreverse(head);}functionprintList(head){letcurr=head;while(curr!=null){console.log(curr.data+" ");curr=curr.next;}console.log();}// Create a hard-coded linked list:// 1 -> 9 -> 9 -> 9lethead=newNode(1);head.next=newNode(9);head.next.next=newNode(9);head.next.next.next=newNode(9);head=addOne(head);printList(head);
Output
2 0 0 0
Time Complexity: O(n), where n is the number of nodes in the linked list. Auxiliary Space: O(1), As constant extra space is used.