Given two non-negative integers represented as linked lists with heads head1 and head2, where each node contains a single digit, return a new linked list representing their sum.
Note: The input lists may contain leading zeros, but the resulting sum list must not contain any leading zeros.
Examples:
Input:
Explanation: Sum of 123 and 999 is 1122.
Input:
Output: 7 -> 0 Explanation: Sum of 63 and 7 is 70.
[Naive Approach] By creating a new list - O(m + n) Time and O(max(m, n)) Space
To sum two linked lists, start by creating an empty linked list, say result, for the sum. Reverse both original linked lists to start from the least significant digit.
Use two pointers to traverse the reversed lists simultaneously. For each pair of nodes, compute their sum and if the sum exceeds 9, store the remainder (sum modulo 10) in the new node and forward the carry to the next pair of nodes. Append each new node to result.
Continue until both lists are fully traversed, handling any remaining nodes from the longer list and carrying over any final carry. Finally, reverse the result linked list to get the sum of the two linked list.
C++
#include<iostream>usingnamespacestd;classNode{public:intdata;Node*next;Node(intval){data=val;next=nullptr;}};// Function to reverse the linked listNode*reverse(Node*head){Node*prev=nullptr,*curr=head,*next;while(curr!=nullptr){next=curr->next;curr->next=prev;prev=curr;curr=next;}returnprev;}// Function to trim leading zeros in linked listNode*trimLeadingZeros(Node*head){while(head->next!=nullptr&&head->data==0)head=head->next;returnhead;}// Function to add two numbers represented by linked listNode*addTwoLists(Node*num1,Node*num2){Node*res=nullptr,*curr=nullptr;intcarry=0;num1=trimLeadingZeros(num1);num2=trimLeadingZeros(num2);num1=reverse(num1);num2=reverse(num2);// Iterate till either num1 is not empty or num2 is// not empty or carry is greater than 0while(num1!=nullptr||num2!=nullptr||carry!=0){intsum=carry;if(num1!=nullptr){sum+=num1->data;num1=num1->next;}if(num2!=nullptr){sum+=num2->data;num2=num2->next;}Node*newNode=newNode(sum%10);carry=sum/10;// If this is the first node, then make this node// as the head of the resultant linked listif(res==nullptr){res=newNode;curr=newNode;}else{// Append new node to resultant linked list// and move to the next nodecurr->next=newNode;curr=curr->next;}}returnreverse(res);}voidprintList(Node*head){Node*curr=head;while(curr!=nullptr){cout<<curr->data;if(curr->next!=NULL){cout<<" -> ";}curr=curr->next;}cout<<"\n";}intmain(){Node*num1=newNode(1);num1->next=newNode(2);num1->next->next=newNode(3);Node*num2=newNode(9);num2->next=newNode(9);num2->next->next=newNode(9);Node*sum=addTwoLists(num1,num2);printList(sum);return0;}
C
#include<stdio.h>structNode{intdata;structNode*next;};structNode*createNode(intval);// Function to reverse the linked liststructNode*reverse(structNode*head){structNode*prev=NULL,*curr=head,*next;while(curr!=NULL){next=curr->next;curr->next=prev;prev=curr;curr=next;}returnprev;}// Function to trim leading zeros in linked liststructNode*trimLeadingZeros(structNode*head){while(head->next!=NULL&&head->data==0)head=head->next;returnhead;}// Function to add two numbers represented by linked liststructNode*addTwoLists(structNode*num1,structNode*num2){structNode*res=NULL,*curr=NULL;intcarry=0;num1=trimLeadingZeros(num1);num2=trimLeadingZeros(num2);num1=reverse(num1);num2=reverse(num2);// Iterate till either num1 is not empty or num2 is// not empty or carry is greater than 0while(num1!=NULL||num2!=NULL||carry!=0){intsum=carry;if(num1!=NULL){sum+=num1->data;num1=num1->next;}if(num2!=NULL){sum+=num2->data;num2=num2->next;}structNode*newNode=createNode(sum%10);carry=sum/10;// If this is the first node, then make this node// as the head of the resultant linked listif(res==NULL){res=newNode;curr=newNode;}else{// Append new node to resultant linked list// and move to the next nodecurr->next=newNode;curr=curr->next;}}returnreverse(res);}voidprintList(structNode*head){structNode*curr=head;while(curr!=NULL){printf("%d",curr->data);if(curr->next!=NULL){printf(" -> ");}curr=curr->next;}printf("\n");}structNode*createNode(intval){structNode*node=(structNode*)malloc(sizeof(structNode));node->data=val;node->next=NULL;returnnode;}intmain(){structNode*num1=createNode(1);num1->next=createNode(2);num1->next->next=createNode(3);structNode*num2=createNode(9);num2->next=createNode(9);num2->next->next=createNode(9);structNode*sum=addTwoLists(num1,num2);printList(sum);return0;}
Java
classNode{intdata;Nodenext;Node(intval){data=val;next=null;}}classGfG{// Function to reverse the linked liststaticNodereverse(Nodehead){Nodeprev=null;Nodecurr=head;Nodenext;while(curr!=null){next=curr.next;curr.next=prev;prev=curr;curr=next;}returnprev;}// Function to trim leading zeros in linked liststaticNodetrimLeadingZeros(Nodehead){while(head!=null&&head.data==0){head=head.next;}returnhead;}// Function to add two numbers represented by linked liststaticNodeaddTwoLists(Nodenum1,Nodenum2){Noderes=null;Nodecurr=null;intcarry=0;num1=trimLeadingZeros(num1);num2=trimLeadingZeros(num2);num1=reverse(num1);num2=reverse(num2);// Iterate till either num1 is not empty or num2 is// not empty or carry is greater than 0while(num1!=null||num2!=null||carry!=0){intsum=carry;if(num1!=null){sum+=num1.data;num1=num1.next;}if(num2!=null){sum+=num2.data;num2=num2.next;}NodenewNode=newNode(sum%10);carry=sum/10;// If this is the first node, then make this node// as the head of the resultant linked listif(res==null){res=newNode;curr=newNode;}else{// Append new node to resultant linked list// and move to the next nodecurr.next=newNode;curr=curr.next;}}returnreverse(res);}staticvoidprintList(Nodehead){Nodecurr=head;while(curr!=null){System.out.print(curr.data);if(curr.next!=null){System.out.print(" -> ");}curr=curr.next;}System.out.println();}publicstaticvoidmain(String[]args){Nodenum1=newNode(1);num1.next=newNode(2);num1.next.next=newNode(3);Nodenum2=newNode(9);num2.next=newNode(9);num2.next.next=newNode(9);Nodesum=addTwoLists(num1,num2);printList(sum);}}
Python
classNode:def__init__(self,val):self.data=valself.next=None# function to reverse the linked listdefreverse(head):prev=Nonecurr=headwhilecurrisnotNone:nextNode=curr.nextcurr.next=prevprev=currcurr=nextNodereturnprev# function to trim leading zeros in linked listdeftrimLeadingZeros(head):whileheadandhead.data==0:head=head.nextreturnhead# Function to add two numbers represented by linked listdefaddTwoLists(num1,num2):res=Nonecurr=Nonecarry=0num1=trimLeadingZeros(num1)num2=trimLeadingZeros(num2)num1=reverse(num1)num2=reverse(num2)# Iterate till either num1 is not empty or num2 is# not empty or carry is greater than 0whilenum1isnotNoneornum2isnotNoneorcarry!=0:sumValue=carryifnum1isnotNone:sumValue+=num1.datanum1=num1.nextifnum2isnotNone:sumValue+=num2.datanum2=num2.nextnewNode=Node(sumValue%10)carry=sumValue//10# If this is the first node, then make this node# as the head of the resultant linked listifresisNone:res=newNodecurr=newNodeelse:# Append new node to resultant linked list# and move to the next nodecurr.next=newNodecurr=curr.nextreturnreverse(res)defprintList(head):curr=headwhilecurrisnotNone:print(curr.data,end="")ifcurr.next!=None:print(" -> ",end="")curr=curr.nextprint()if__name__=="__main__":num1=Node(1)num1.next=Node(2)num1.next.next=Node(3)num2=Node(9)num2.next=Node(9)num2.next.next=Node(9)sumList=addTwoLists(num1,num2)printList(sumList)
C#
usingSystem;classNode{publicintdata;publicNodenext;publicNode(intval){data=val;next=null;}}classGfG{// Function to reverse the linked liststaticNodereverse(Nodehead){Nodeprev=null;Nodecurr=head;Nodenext;while(curr!=null){next=curr.next;curr.next=prev;prev=curr;curr=next;}returnprev;}// function to trim leading zeros in linked liststaticNodetrimLeadingZeros(Nodehead){while(head!=null&&head.data==0){head=head.next;}returnhead;}// Function to add two numbers represented by linked liststaticNodeaddTwoLists(Nodenum1,Nodenum2){Noderes=null;Nodecurr=null;intcarry=0;num1=trimLeadingZeros(num1);num2=trimLeadingZeros(num2);num1=reverse(num1);num2=reverse(num2);// Iterate till either num1 is not empty or num2 is// not empty or carry is greater than 0while(num1!=null||num2!=null||carry!=0){intsum=carry;if(num1!=null){sum+=num1.data;num1=num1.next;}if(num2!=null){sum+=num2.data;num2=num2.next;}NodenewNode=newNode(sum%10);carry=sum/10;// If this is the first node, then make this node// as the head of the resultant linked listif(res==null){res=newNode;curr=newNode;}else{// Append new node to resultant linked list// and move to the next nodecurr.next=newNode;curr=curr.next;}}returnreverse(res);}staticvoidprintList(Nodehead){Nodecurr=head;while(curr!=null){Console.Write(curr.data);if(curr.next!=null){Console.Write(" -> ");}curr=curr.next;}Console.WriteLine();}staticvoidMain(){Nodenum1=newNode(1);num1.next=newNode(2);num1.next.next=newNode(3);Nodenum2=newNode(9);num2.next=newNode(9);num2.next.next=newNode(9);Nodesum=addTwoLists(num1,num2);printList(sum);}}
JavaScript
classNode{constructor(val){this.data=val;this.next=null;}}// Function to reverse the linked listfunctionreverse(head){letprev=null;letcurr=head;letnext;while(curr!==null){next=curr.next;curr.next=prev;prev=curr;curr=next;}returnprev;}// function to trim leading zeros in linked listfunctiontrimLeadingZeros(head){while(head!==null&&head.data===0){head=head.next;}returnhead;}// Function to add two numbers represented by linked listfunctionaddTwoLists(num1,num2){letres=null;letcurr=null;letcarry=0;num1=trimLeadingZeros(num1);num2=trimLeadingZeros(num2);num1=reverse(num1);num2=reverse(num2);// Iterate till either num1 is not empty or num2 is// not empty or carry is greater than 0while(num1!==null||num2!==null||carry!==0){letsum=carry;if(num1!==null){sum+=num1.data;num1=num1.next;}if(num2!==null){sum+=num2.data;num2=num2.next;}letnewNode=newNode(sum%10);carry=Math.floor(sum/10);// If this is the first node, then make this node// as the head of the resultant linked listif(res===null){res=newNode;curr=newNode;}else{// Append new node to resultant linked list// and move to the next nodecurr.next=newNode;curr=curr.next;}}returnreverse(res);}functionprintList(head){letcurr=head;letresult='';while(curr!==null){result+=curr.data;if(curr.next!==null){result+=" -> ";}curr=curr.next;}console.log(result.trim());}// Driver Codeletnum1=newNode(1);num1.next=newNode(2);num1.next.next=newNode(3);letnum2=newNode(9);num2.next=newNode(9);num2.next.next=newNode(9);letsum=addTwoLists(num1,num2);printList(sum);
Output
1 -> 1 -> 2 -> 2
[Expected Approach] By storing sum on the longer list - O(m + n) Time and O(1) Space
The idea is to first reverse both linked lists so that addition can be performed starting from the least significant digit. We then iterate through both lists simultaneously, adding corresponding digits along with any carry. For each sum, we create a new node and insert it at the front of the result list.
After processing all nodes, if a carry remains, we add a new node for it. Finally, the resulting list represents the sum without any leading zeros.
Illustrations:
C++
#include<iostream>usingnamespacestd;classNode{public:intdata;Node*next;Node(intval){data=val;next=nullptr;}};// Function to reverse a linked listNode*reverse(Node*head){Node*prev=nullptr,*curr=head,*next;while(curr!=nullptr){next=curr->next;curr->next=prev;prev=curr;curr=next;}returnprev;}Node*addTwoLists(Node*head1,Node*head2){// Reverse both lists to start from least significant digithead1=reverse(head1);head2=reverse(head2);Node*sum=NULL;intcarry=0;// Traverse both lists until all digits and carry are processedwhile(head1!=NULL||head2!=NULL||carry!=0){intnewVal=carry;if(head1){newVal+=head1->data;head1=head1->next;}if(head2){newVal+=head2->data;head2=head2->next;}carry=newVal/10;newVal%=10;// Insert the new digit at the front of the result listNode*newNode=newNode(newVal);newNode->next=sum;sum=newNode;}// Remove leading zeros, if anywhile(sum!=NULL&&sum->data==0){Node*temp=sum;sum=sum->next;deletetemp;}// If result is empty, return single node with 0if(sum==NULL){returnnewNode(0);}returnsum;}voidprintList(Node*head){Node*curr=head;while(curr!=nullptr){cout<<curr->data;if(curr->next!=NULL){cout<<" -> ";}curr=curr->next;}cout<<"\n";}intmain(){Node*num1=newNode(1);num1->next=newNode(2);num1->next->next=newNode(3);Node*num2=newNode(9);num2->next=newNode(9);num2->next->next=newNode(9);Node*sum=addTwoLists(num1,num2);printList(sum);return0;}
C
#include<stdio.h>structNode{intdata;structNode*next;};structNode*createNode(intval);// Function to create a new nodestructNode*newNode(intdata){structNode*node=(structNode*)malloc(sizeof(structNode));node->data=data;node->next=NULL;returnnode;}// Function to reverse a linked liststructNode*reverse(structNode*head){structNode*prev=NULL,*curr=head,*next;while(curr!=NULL){next=curr->next;curr->next=prev;prev=curr;curr=next;}returnprev;}// Function to add two linked listsstructNode*addTwoLists(structNode*head1,structNode*head2){// Reverse both lists to start // from least significant digithead1=reverse(head1);head2=reverse(head2);structNode*sum=NULL;intcarry=0;// Traverse both lists until all// digits and carry are processedwhile(head1!=NULL||head2!=NULL||carry!=0){intnewVal=carry;if(head1){newVal+=head1->data;head1=head1->next;}if(head2){newVal+=head2->data;head2=head2->next;}carry=newVal/10;newVal%=10;// Insert the new digit at the front of the result liststructNode*node=newNode(newVal);node->next=sum;sum=node;}// Remove leading zeros, if anywhile(sum!=NULL&&sum->data==0){structNode*temp=sum;sum=sum->next;free(temp);}// If result is empty, return single node with 0if(sum==NULL){returnnewNode(0);}returnsum;}voidprintList(structNode*head){structNode*curr=head;while(curr!=NULL){printf("%d",curr->data);if(curr->next!=NULL)printf(" -> ");curr=curr->next;}printf("\n");}structNode*createNode(intval){structNode*node=(structNode*)malloc(sizeof(structNode));node->data=val;node->next=NULL;returnnode;}intmain(){structNode*num1=createNode(1);num1->next=createNode(2);num1->next->next=createNode(3);structNode*num2=createNode(9);num2->next=createNode(9);num2->next->next=createNode(9);structNode*sum=addTwoLists(num1,num2);printList(sum);return0;}
Java
classNode{intdata;Nodenext;Node(intval){data=val;next=null;}}classGfG{// Function to reverse the linked liststaticNodereverse(Nodehead){Nodeprev=null,curr=head,next=null;while(curr!=null){next=curr.next;curr.next=prev;prev=curr;curr=next;}returnprev;}staticNodeaddTwoLists(Nodehead1,Nodehead2){// Reverse both lists to start// from least significant digithead1=reverse(head1);head2=reverse(head2);Nodesum=null;intcarry=0;// Traverse until both lists// and carry are processedwhile(head1!=null||head2!=null||carry>0){intnewVal=carry;if(head1!=null){newVal+=head1.data;head1=head1.next;}if(head2!=null){newVal+=head2.data;head2=head2.next;}carry=newVal/10;newVal%=10;// Create new node and insert// at front of result listNodenewNode=newNode(newVal);newNode.next=sum;sum=newNode;}// Remove leading zeros if presentwhile(sum!=null&&sum.data==0){sum=sum.next;}return(sum==null)?newNode(0):sum;}staticvoidprintList(Nodehead){Nodecurr=head;while(curr!=null){System.out.print(curr.data);if(curr.next!=null){System.out.print(" -> ");}curr=curr.next;}System.out.println();}publicstaticvoidmain(String[]args){Nodenum1=newNode(1);num1.next=newNode(2);num1.next.next=newNode(3);Nodenum2=newNode(9);num2.next=newNode(9);num2.next.next=newNode(9);Nodesum=addTwoLists(num1,num2);printList(sum);}}
Python
classNode:def__init__(self,val):self.data=valself.next=None# Function to reverse the linked listdefreverse(head):prev=Nonecurrent=headwhilecurrentisnotNone:next=current.nextcurrent.next=prevprev=currentcurrent=nextreturnprevdefaddTwoLists(head1,head2):# Reverse both lists to simplify additionhead1=reverse(head1)head2=reverse(head2)sumList=Nonecarry=0# Loop until both lists and carry are exhaustedwhilehead1isnotNoneorhead2isnotNoneorcarry>0:newVal=carryifhead1isnotNone:newVal+=head1.datahead1=head1.nextifhead2isnotNone:newVal+=head2.datahead2=head2.nextcarry=newVal//10newVal=newVal%10# Create a new node and link it at the frontnewNode=Node(newVal)newNode.next=sumListsumList=newNode# Return the final sum listreturnsumListdefprintList(head):curr=headwhilecurrisnotNone:print(curr.data,end="")ifcurr.nextisnotNone:print(" -> ",end="")curr=curr.nextprint()if__name__=="__main__":num1=Node(1)num1.next=Node(2)num1.next.next=Node(3)num2=Node(9)num2.next=Node(9)num2.next.next=Node(9)sumList=addTwoLists(num1,num2)printList(sumList)
C#
usingSystem;classNode{publicintdata;publicNodenext;publicNode(intval){data=val;next=null;}}classGfG{// Function to reverse a linked liststaticNodereverse(Nodehead){Nodeprev=null;Nodecurrent=head;Nodenext;while(current!=null){next=current.next;current.next=prev;prev=current;current=next;}returnprev;}staticNodeaddTwoLists(Nodehead1,Nodehead2){// Reverse both lists to simplify additionhead1=reverse(head1);head2=reverse(head2);Nodesum=null;intcarry=0;// Loop while nodes remain or carry is non-zerowhile(head1!=null||head2!=null||carry!=0){intnewVal=carry;if(head1!=null){newVal+=head1.data;head1=head1.next;}if(head2!=null){newVal+=head2.data;head2=head2.next;}carry=newVal/10;newVal=newVal%10;NodenewNode=newNode(newVal);newNode.next=sum;sum=newNode;}// Remove leading zeroswhile(sum!=null&&sum.data==0){sum=sum.next;}return(sum!=null)?sum:newNode(0);}staticvoidprintList(Nodehead){Nodecurr=head;while(curr!=null){Console.Write(curr.data);if(curr.next!=null){Console.Write(" -> ");}curr=curr.next;}Console.WriteLine();}staticvoidMain(){Nodenum1=newNode(1);num1.next=newNode(2);num1.next.next=newNode(3);Nodenum2=newNode(9);num2.next=newNode(9);num2.next.next=newNode(9);Nodesum=addTwoLists(num1,num2);printList(sum);}}
JavaScript
classNode{constructor(val){this.data=val;this.next=null;}}// function to reverse a linked listfunctionreverse(head){letprev=null;letcurrent=head;letnext;while(current!==null){next=current.next;current.next=prev;prev=current;current=next;}returnprev;}functionaddTwoLists(head1,head2){// reverse both lists to start // from least significant digithead1=reverse(head1);head2=reverse(head2);letsum=null;letcarry=0;// loop until both lists and // carry are exhaustedwhile(head1!==null||head2!==null||carry!==0){letnewVal=carry;if(head1){newVal+=head1.data;head1=head1.next;}if(head2){newVal+=head2.data;head2=head2.next;}carry=Math.floor(newVal/10);newVal=newVal%10;letnewNode=newNode(newVal);newNode.next=sum;sum=newNode;}// remove leading zeroswhile(sum!==null&&sum.data===0){sum=sum.next;}returnsum===null?newNode(0):sum;}functionprintList(head){letcurr=head;letresult="";while(curr!==null){result+=curr.data;if(curr.next!==null){result+=" -> ";}curr=curr.next;}console.log(result.trim());}// Driver Codeletnum1=newNode(1);num1.next=newNode(2);num1.next.next=newNode(3);letnum2=newNode(9);num2.next=newNode(9);num2.next.next=newNode(9);letsum=addTwoLists(num1,num2);printList(sum);
Output
1 -> 1 -> 2 -> 2
[Other Approach] Using Recursion - O(m + n) Time and O(max(m, n)) Space
The idea is to use recursionto compute the sum. Recursively move to the end of the lists, calculate the sum of the last nodes (including any carry from previous additions), while backtracking add up the sums together.