The idea is to use recursion to compute the sum. Reverse both the linked lists to start from the least significant digit. Now, traverse both the linked list recursively and in each recursive add the values of the current nodes and the carry from the previous step (initially, carry = 0). If there is a carry after the last nodes, append a new node with this carry. Finally, reverse the linked list to get the sum.
C++
// C++ code to add two linked list using recursion#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;Node*curr=head;Node*next=nullptr;// Loop to reverse the linked listwhile(curr!=nullptr){next=curr->next;curr->next=prev;prev=curr;curr=next;}returnprev;}// Recursive function to add two numbers represented// by linked listsNode*addListRec(Node*num1,Node*num2,int&carry){// Base case: If both lists are empty and no carry is leftif(num1==nullptr&&num2==nullptr&&carry==0){returnnullptr;}intsum=carry;// Add the value from the first list if it existsif(num1!=nullptr){sum+=num1->data;num1=num1->next;}// Add the value from the second list if it existsif(num2!=nullptr){sum+=num2->data;num2=num2->next;}carry=sum/10;Node*result=newNode(sum%10);// Recursively add remaining digitsresult->next=addListRec(num1,num2,carry);returnresult;}// function to trim leading zeros in linked listNode*trimLeadingZeros(Node*head){while(head!=nullptr&&head->data==0){head=head->next;}returnhead;}// function for adding two linked listsNode*addTwoLists(Node*num1,Node*num2){num1=trimLeadingZeros(num1);num2=trimLeadingZeros(num2);// Reverse both lists to start addition from // the least significant digitnum1=reverse(num1);num2=reverse(num2);intcarry=0;Node*result=addListRec(num1,num2,carry);// If there's any carry left after the addition,// create a new node for itif(carry!=0){Node*newNode=newNode(carry);newNode->next=result;result=newNode;}// Reverse the result list to restore// the original orderreturnreverse(result);}voidprintList(Node*head){Node*curr=head;while(curr!=nullptr){cout<<curr->data<<" ";curr=curr->next;}cout<<"\n";}intmain(){// Creating first linked list: 1 -> 2 -> 3 // (represents 123)Node*num1=newNode(1);num1->next=newNode(2);num1->next->next=newNode(3);// Creating second linked list: 9 -> 9 -> 9 // (represents 999)Node*num2=newNode(9);num2->next=newNode(9);num2->next->next=newNode(9);Node*sum=addTwoLists(num1,num2);printList(sum);return0;}
C
// C code to add two linked list using recursion #include<stdio.h>structNode{intdata;structNode*next;};// Function to create a new nodestructNode*createNode(intval){structNode*newNode=(structNode*)malloc(sizeof(structNode));newNode->data=val;newNode->next=NULL;returnnewNode;}// Function to reverse a linked liststructNode*reverse(structNode*head){structNode*prev=NULL;structNode*curr=head;structNode*next=NULL;// Loop to reverse the linked listwhile(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;}// Recursive function to add two numbers represented by linked listsstructNode*addListRec(structNode*num1,structNode*num2,int*carry){// Base case: If both lists are empty and no carry is leftif(num1==NULL&&num2==NULL&&*carry==0){returnNULL;}intsum=*carry;// Add the value from the first list if it existsif(num1!=NULL){sum+=num1->data;num1=num1->next;}// Add the value from the second list if it existsif(num2!=NULL){sum+=num2->data;num2=num2->next;}*carry=sum/10;structNode*result=createNode(sum%10);// Recursively add remaining digitsresult->next=addListRec(num1,num2,carry);returnresult;}// Function for adding two linked listsstructNode*addTwoLists(structNode*num1,structNode*num2){num1=trimLeadingZeros(num1);num2=trimLeadingZeros(num2);// Reverse both lists to start addition from the // least significant digitnum1=reverse(num1);num2=reverse(num2);intcarry=0;structNode*result=addListRec(num1,num2,&carry);// If there's any carry left after the addition,// create a new node for itif(carry!=0){structNode*newNode=createNode(carry);newNode->next=result;result=newNode;}// Reverse the result list to restore the original orderreturnreverse(result);}// Function to print a linked listvoidprintList(structNode*head){structNode*curr=head;while(curr!=NULL){printf("%d ",curr->data);curr=curr->next;}printf("\n");}intmain(){// Creating first linked list: 1 -> 2 -> 3 (represents 123)structNode*num1=createNode(1);num1->next=createNode(2);num1->next->next=createNode(3);// Creating second linked list: 9 -> 9 -> 9 (represents 999)structNode*num2=createNode(9);num2->next=createNode(9);num2->next->next=createNode(9);structNode*sum=addTwoLists(num1,num2);printList(sum);return0;}
Java
// Java code to add two linked list using recursionclassNode{intdata;Nodenext;Node(intval){data=val;next=null;}}classGfG{// Function to reverse a linked liststaticNodereverse(Nodehead){Nodeprev=null;Nodecurr=head;Nodenext=null;// Loop to reverse the linked listwhile(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;}// Recursive function to add two numbers // represented by linked listsstaticNodeaddListRec(Nodenum1,Nodenum2,int[]carry){// Base case: If both lists are empty // and no carry is leftif(num1==null&&num2==null&&carry[0]==0){returnnull;}intsum=carry[0];// Add the value from the first list if it existsif(num1!=null){sum+=num1.data;num1=num1.next;}// Add the value from the second list if it existsif(num2!=null){sum+=num2.data;num2=num2.next;}carry[0]=sum/10;Noderesult=newNode(sum%10);// Recursively add remaining digitsresult.next=addListRec(num1,num2,carry);returnresult;}// Function for adding two linked listsstaticNodeaddTwoLists(Nodenum1,Nodenum2){num1=trimLeadingZeros(num1);num2=trimLeadingZeros(num2);// Reverse both lists to start addition from // the least significant digitnum1=reverse(num1);num2=reverse(num2);// Array used to pass carry by referenceint[]carry=newint[1];Noderesult=addListRec(num1,num2,carry);// If there's any carry left after the addition, // create a new node for itif(carry[0]!=0){NodenewNode=newNode(carry[0]);newNode.next=result;result=newNode;}// Reverse the list to restore the original orderreturnreverse(result);}// Function to print a linked liststaticvoidprintList(Nodehead){Nodecurr=head;while(curr!=null){System.out.print(curr.data+" ");curr=curr.next;}System.out.println();}publicstaticvoidmain(String[]args){// Creating first linked list: // 1 -> 2 -> 3 (represents 123)Nodenum1=newNode(1);num1.next=newNode(2);num1.next.next=newNode(3);// Creating second linked list: // 9 -> 9 -> 9 (represents 999)Nodenum2=newNode(9);num2.next=newNode(9);num2.next.next=newNode(9);Nodesum=addTwoLists(num1,num2);printList(sum);}}
Python
# Python code to add two linked lists using recursionimportsysclassNode:def__init__(self,val):self.data=valself.next=None# Function to reverse a linked listdefreverse(head):prev=Nonecurr=headnext=None# Loop to reverse the linked listwhilecurrisnotNone:next=curr.nextcurr.next=prevprev=currcurr=nextreturnprev# function to trim leading zeros from linked listdeftrimLeadingZeros(head):whileheadandhead.data==0:head=head.nextreturnhead# Recursive function to add two numbers represented# by linked listsdefaddListRec(num1,num2,carry):# Base case: If both lists are empty and no carry is leftifnum1isNoneandnum2isNoneandcarry[0]==0:returnNonesum=carry[0]# Add the value from the first list if it existsifnum1isnotNone:sum+=num1.datanum1=num1.next# Add the value from the second list if it existsifnum2isnotNone:sum+=num2.datanum2=num2.nextcarry[0]=sum//10result=Node(sum%10)# Recursively add remaining digitsresult.next=addListRec(num1,num2,carry)returnresult# Function for adding two linked listsdefaddTwoLists(num1,num2):num1=trimLeadingZeros(num1)num2=trimLeadingZeros(num2)# Reverse both lists to start addition from the # least significant digitnum1=reverse(num1)num2=reverse(num2)carry=[0]result=addListRec(num1,num2,carry)# If there's any carry left after the addition,# create a new node for itifcarry[0]!=0:newNode=Node(carry[0])newNode.next=resultresult=newNode# Reverse the result list to restore the original orderreturnreverse(result)defprintList(head):curr=headwhilecurrisnotNone:print(curr.data,end=' ')curr=curr.nextprint()if__name__=="__main__":# Creating first linked list: # 1 -> 2 -> 3 (represents 123)num1=Node(1)num1.next=Node(2)num1.next.next=Node(3)# Creating second linked list: # 9 -> 9 -> 9 (represents 999)num2=Node(9)num2.next=Node(9)num2.next.next=Node(9)sumList=addTwoLists(num1,num2)printList(sumList)
C#
// C# code to add two linked list using recursionusingSystem;classNode{publicintdata;publicNodenext;publicNode(intval){data=val;next=null;}}// Function to reverse a linked listclassGfG{staticNodeReverse(Nodehead){Nodeprev=null;Nodecurr=head;Nodenext=null;// Loop to reverse the linked listwhile(curr!=null){next=curr.next;curr.next=prev;prev=curr;curr=next;}returnprev;}// Function to trim leading zeros from linked liststaticNodeTrimLeadingZeros(Nodehead){while(head!=null&&head.data==0){head=head.next;}returnhead;}// Recursive function to add two numbers represented// by linked listsstaticNodeAddListRec(Nodenum1,Nodenum2,refintcarry){num1=TrimLeadingZeros(num1);num2=TrimLeadingZeros(num2);// Base case: If both lists are empty and// no carry is leftif(num1==null&&num2==null&&carry==0){returnnull;}intsum=carry;// Add the value from the first list if it existsif(num1!=null){sum+=num1.data;num1=num1.next;}// Add the value from the second list if it existsif(num2!=null){sum+=num2.data;num2=num2.next;}carry=sum/10;Noderesult=newNode(sum%10);// Recursively add remaining digitsresult.next=AddListRec(num1,num2,refcarry);returnresult;}// Function for adding two linked listsstaticNodeAddTwoLists(Nodenum1,Nodenum2){// Reverse both lists to start addition from // the least significant digitnum1=Reverse(num1);num2=Reverse(num2);intcarry=0;Noderesult=AddListRec(num1,num2,refcarry);// If there's any carry left after the addition,// create a new node for itif(carry!=0){NodenewNode=newNode(carry);newNode.next=result;result=newNode;}// Reverse the result list to restore// the original orderreturnReverse(result);}staticvoidPrintList(Nodehead){Nodecurr=head;while(curr!=null){Console.Write(curr.data+" ");curr=curr.next;}Console.WriteLine();}staticvoidMain(){// Creating first linked list: 1 -> 2 -> 3 // (represents 123)Nodenum1=newNode(1);num1.next=newNode(2);num1.next.next=newNode(3);// Creating second linked list: 9 -> 9 -> 9 // (represents 999)Nodenum2=newNode(9);num2.next=newNode(9);num2.next.next=newNode(9);Nodesum=AddTwoLists(num1,num2);PrintList(sum);}}
JavaScript
// Javascript code to add two linked list using recursionclassNode{constructor(val){this.data=val;this.next=null;}}// Function to reverse a linked listfunctionreverse(head){letprev=null;letcurr=head;letnext=null;// Loop to reverse the linked listwhile(curr!==null){next=curr.next;curr.next=prev;prev=curr;curr=next;}returnprev;}functiontrimLeadingZeros(head){while(head!==null&&head.data===0){head=head.next;}returnhead;}// Recursive function to add two numbers represented// by linked listsfunctionaddListRec(num1,num2,carry){// Base case: If both lists are empty and no carry is leftif(num1===null&&num2===null&&carry===0){returnnull;}letsum=carry;// Add the value from the first list if it existsif(num1!==null){sum+=num1.data;num1=num1.next;}// Add the value from the second list if it existsif(num2!==null){sum+=num2.data;num2=num2.next;}carry=Math.floor(sum/10);letresult=newNode(sum%10);// Recursively add remaining digitsresult.next=addListRec(num1,num2,carry);returnresult;}// Function for adding two linked listsfunctionaddTwoLists(num1,num2){num1=trimLeadingZeros(num1);num2=trimLeadingZeros(num2);// Reverse both lists to start addition from// the least significant digitnum1=reverse(num1);num2=reverse(num2);letcarry=0;letresult=addListRec(num1,num2,carry);// If there's any carry left after the addition,// create a new node for itif(carry!==0){letnewNode=newNode(carry);newNode.next=result;result=newNode;}// Reverse the result list to restore// the original orderreturnreverse(result);}functionprintList(head){letcurr=head;letresult='';while(curr!==null){result+=curr.data+' ';curr=curr.next;}console.log(result.trim());}// Creating first linked list: 1 -> 2 -> 3// (represents 123)letnum1=newNode(1);num1.next=newNode(2);num1.next.next=newNode(3);// Creating second linked list: 9 -> 9 -> 9// (represents 999)letnum2=newNode(9);num2.next=newNode(9);num2.next.next=newNode(9);letsum=addTwoLists(num1,num2);printList(sum);
Output
1 1 2 2
Time Complexity: O(m + n), where m and n are the sizes of given two linked lists. Auxiliary Space: O(max(m, n))