Given two polynomial numbers represented by a linked list. The task is to add these lists meaning the coefficients with the same variable powers will be added. Note: Given polynomials are sorted in decreasing order of power.
[Expected Approach - 1] Using Recursion - O(m+n) Time and O(max(m,n)) Space:
The idea is to recursively check the heads of both lists. If one of the heads is NULL, then return the other head. Otherwise, compare the power of both nodes. If the power of one list is greater than the other, then recursively find the next node of the greater power list. Otherwise, store the sum of coefficients in one list, and return its head.
Below is the implementation of the above approach:
C++
// C++ program to add two polynomials#include<bits/stdc++.h>usingnamespacestd;classNode{public:intcoeff;intpow;Node*next;Node(intc,intp){coeff=c;pow=p;next=nullptr;}};Node*addPolynomial(Node*head1,Node*head2){// if any list is empty, then return// the other list.if(head1==nullptr)returnhead2;if(head2==nullptr)returnhead1;// If head1.pow is greater, then recursively find// its next node, and return head1.if(head1->pow>head2->pow){Node*nextPtr=addPolynomial(head1->next,head2);head1->next=nextPtr;returnhead1;}// If head2.pow is greater, then recusrively find its // next node, and return head2.elseif(head1->pow<head2->pow){Node*nextPtr=addPolynomial(head1,head2->next);head2->next=nextPtr;returnhead2;}// else store the sum of head1.coeff and head2.coeff in// head1->coeff, then find its next node and return head1.Node*nextPtr=addPolynomial(head1->next,head2->next);head1->coeff+=head2->coeff;head1->next=nextPtr;returnhead1;}voidprintList(Node*head){Node*curr=head;while(curr!=nullptr){cout<<curr->coeff<<","<<curr->pow<<" ";curr=curr->next;}cout<<endl;}intmain(){// 1st polynomial: 5x^2+4x^1+2x^0Node*head1=newNode(5,2);head1->next=newNode(4,1);head1->next->next=newNode(2,0);// 2nd polynomial: -5x^1-5x^0Node*head2=newNode(-5,1);head2->next=newNode(-5,0);Node*head=addPolynomial(head1,head2);printList(head);}
C
// C program to add two polynomials#include<stdio.h>#include<stdlib.h>structNode{intcoeff;intpow;structNode*next;};structNode*createNode(intc,intp);structNode*addPolynomial(structNode*head1,structNode*head2){// if any list is empty, then return// the other list.if(head1==NULL)returnhead2;if(head2==NULL)returnhead1;// If head1.pow is greater, then recursively find// its next node, and return head1.if(head1->pow>head2->pow){structNode*nextPtr=addPolynomial(head1->next,head2);head1->next=nextPtr;returnhead1;}// If head2.pow is greater, then recursively find its // next node, and return head2.elseif(head1->pow<head2->pow){structNode*nextPtr=addPolynomial(head1,head2->next);head2->next=nextPtr;returnhead2;}// else store the sum of head1.coeff and head2.coeff in// head1->coeff, then find its next node and return head1.structNode*nextPtr=addPolynomial(head1->next,head2->next);head1->coeff+=head2->coeff;head1->next=nextPtr;returnhead1;}voidprintList(structNode*head){structNode*curr=head;while(curr!=NULL){printf("%d,%d ",curr->coeff,curr->pow);curr=curr->next;}printf("\n");}structNode*createNode(intc,intp){structNode*newNode=(structNode*)malloc(sizeof(structNode));newNode->coeff=c;newNode->pow=p;newNode->next=NULL;returnnewNode;}intmain(){// 1st polynomial: 5x^2+4x^1+2x^0structNode*head1=createNode(5,2);head1->next=createNode(4,1);head1->next->next=createNode(2,0);// 2nd polynomial: -5x^1-5x^0structNode*head2=createNode(-5,1);head2->next=createNode(-5,0);structNode*head=addPolynomial(head1,head2);printList(head);return0;}
Java
// Java program to add two polynomialsclassNode{intcoeff;intpow;Nodenext;Node(intc,intp){coeff=c;pow=p;next=null;}}classMain{staticNodeaddPolynomial(Nodehead1,Nodehead2){// if any list is empty, then return// the other list.if(head1==null)returnhead2;if(head2==null)returnhead1;// If head1.pow is greater, then recursively find// its next node, and return head1.if(head1.pow>head2.pow){NodenextPtr=addPolynomial(head1.next,head2);head1.next=nextPtr;returnhead1;}// If head2.pow is greater, then recursively find its // next node, and return head2.elseif(head1.pow<head2.pow){NodenextPtr=addPolynomial(head1,head2.next);head2.next=nextPtr;returnhead2;}// else store the sum of head1.coeff and head2.coeff in// head1.coeff, then find its next node and return head1.NodenextPtr=addPolynomial(head1.next,head2.next);head1.coeff+=head2.coeff;head1.next=nextPtr;returnhead1;}staticvoidprintList(Nodehead){Nodecurr=head;while(curr!=null){System.out.print(curr.coeff+","+curr.pow+" ");curr=curr.next;}System.out.println();}publicstaticvoidmain(String[]args){// 1st polynomial: 5x^2+4x^1+2x^0Nodehead1=newNode(5,2);head1.next=newNode(4,1);head1.next.next=newNode(2,0);// 2nd polynomial: -5x^1-5x^0Nodehead2=newNode(-5,1);head2.next=newNode(-5,0);Nodehead=addPolynomial(head1,head2);printList(head);}}
Python
# Python program to add two polynomialsclassNode:def__init__(self,c,p):self.coeff=cself.pow=pself.next=Nonedefadd_polynomial(head1,head2):# if any list is empty, then return# the other list.ifhead1isNone:returnhead2ifhead2isNone:returnhead1# If head1.pow is greater, then recursively find# its next node, and return head1.ifhead1.pow>head2.pow:next_ptr=add_polynomial(head1.next,head2)head1.next=next_ptrreturnhead1# If head2.pow is greater, then recursively find its # next node, and return head2.elifhead1.pow<head2.pow:next_ptr=add_polynomial(head1,head2.next)head2.next=next_ptrreturnhead2# else store the sum of head1.coeff and head2.coeff in# head1.coeff, then find its next node and return head1.next_ptr=add_polynomial(head1.next,head2.next)head1.coeff+=head2.coeffhead1.next=next_ptrreturnhead1defprint_list(head):curr=headwhilecurrisnotNone:print(f"{curr.coeff},{curr.pow}",end=" ")curr=curr.nextprint()if__name__=="__main__":# 1st polynomial: 5x^2+4x^1+2x^0head1=Node(5,2)head1.next=Node(4,1)head1.next.next=Node(2,0)# 2nd polynomial: -5x^1-5x^0head2=Node(-5,1)head2.next=Node(-5,0)head=add_polynomial(head1,head2)print_list(head)
C#
// C# program to add two polynomialsclassNode{publicintcoeff;publicintpow;publicNodenext;publicNode(intc,intp){coeff=c;pow=p;next=null;}}classGfG{staticNodeAddPolynomial(Nodehead1,Nodehead2){// if any list is empty, then return// the other list.if(head1==null)returnhead2;if(head2==null)returnhead1;NodenextPtr;// If head1.pow is greater, then recursively find// its next node, and return head1.if(head1.pow>head2.pow){nextPtr=AddPolynomial(head1.next,head2);head1.next=nextPtr;returnhead1;}// If head2.pow is greater, then recursively find its // next node, and return head2.elseif(head1.pow<head2.pow){nextPtr=AddPolynomial(head1,head2.next);head2.next=nextPtr;returnhead2;}// else store the sum of head1.coeff and head2.coeff in// head1.coeff, then find its next node and return head1.nextPtr=AddPolynomial(head1.next,head2.next);head1.coeff+=head2.coeff;head1.next=nextPtr;returnhead1;}staticvoidPrintList(Nodehead){Nodecurr=head;while(curr!=null){System.Console.Write(curr.coeff+","+curr.pow+" ");curr=curr.next;}System.Console.WriteLine();}staticvoidMain(string[]args){// 1st polynomial: 5x^2+4x^1+2x^0Nodehead1=newNode(5,2);head1.next=newNode(4,1);head1.next.next=newNode(2,0);// 2nd polynomial: -5x^1-5x^0Nodehead2=newNode(-5,1);head2.next=newNode(-5,0);Nodehead=AddPolynomial(head1,head2);PrintList(head);}}
JavaScript
// JavaScript program to add two polynomialsclassNode{constructor(c,p){this.coeff=c;this.pow=p;this.next=null;}}functionaddPolynomial(head1,head2){// if any list is empty, then return// the other list.if(head1===null)returnhead2;if(head2===null)returnhead1;// If head1.pow is greater, then recursively find// its next node, and return head1.if(head1.pow>head2.pow){letnextPtr=addPolynomial(head1.next,head2);head1.next=nextPtr;returnhead1;}// If head2.pow is greater, then recursively find its // next node, and return head2.elseif(head1.pow<head2.pow){letnextPtr=addPolynomial(head1,head2.next);head2.next=nextPtr;returnhead2;}// else store the sum of head1.coeff and head2.coeff in// head1.coeff, then find its next node and return head1.letnextPtr=addPolynomial(head1.next,head2.next);head1.coeff+=head2.coeff;head1.next=nextPtr;returnhead1;}functionprintList(head){letcurr=head;while(curr!==null){console.log(curr.coeff+","+curr.pow+" ");curr=curr.next;}console.log();}// 1st polynomial: 5x^2+4x^1+2x^0lethead1=newNode(5,2);head1.next=newNode(4,1);head1.next.next=newNode(2,0);// 2nd polynomial: -5x^1-5x^0lethead2=newNode(-5,1);head2.next=newNode(-5,0);lethead=addPolynomial(head1,head2);printList(head);
Output
5,2 -1,1 -3,0
Time Complexity: O(m+n), where m and n are the number of nodes in both the lists. Auxiliary Space: O(max(m,n))
[Expected Approach] Using Iterative Method - O(m+n) Time and O(1) Space:
The idea is to create a dummy node which will act as the head of resultant list. Start traversing both the lists, if list1->pow if not equal to list2->pow, then Link the node with greater power to the resultant list. Otherwise, add the sum of list1->coeff + list2->coeff to the resultant list.
Below is the implementation of the above approach:
C++
// C++ program to add two polynomials#include<bits/stdc++.h>usingnamespacestd;classNode{public:intcoeff;intpow;Node*next;Node(intc,intp){coeff=c;pow=p;next=nullptr;}};Node*addPolynomial(Node*head1,Node*head2){Node*dummy=newNode(0,0);// Node to append other nodes to the end // of listNode*prev=dummy;Node*curr1=head1,*curr2=head2;while(curr1!=nullptr&&curr2!=nullptr){// if curr2.pow > curr1.pow, then // append curr2 to listif(curr1->pow<curr2->pow){prev->next=curr2;prev=curr2;curr2=curr2->next;}// if curr1.pow > curr2.pow, then // append curr2 to listelseif(curr1->pow>curr2->pow){prev->next=curr1;prev=curr1;curr1=curr1->next;}// else, add the sum of curr1->coeff and // curr2->coeff to curr1->coeff, and append// curr1 to the listelse{curr1->coeff=curr1->coeff+curr2->coeff;prev->next=curr1;prev=curr1;curr1=curr1->next;curr2=curr2->next;}}// if curr1 if not null, then append the rest// to the listif(curr1!=nullptr){prev->next=curr1;}// if curr2 if not null, then append the rest// to the listif(curr2!=NULL){prev->next=curr2;}returndummy->next;}voidprintList(Node*head){Node*curr=head;while(curr!=nullptr){cout<<curr->coeff<<","<<curr->pow<<" ";curr=curr->next;}cout<<endl;}intmain(){// 1st polynomial: 5x^2+4x^1+2x^0Node*head1=newNode(5,2);head1->next=newNode(4,1);head1->next->next=newNode(2,0);// 2nd polynomial: -5x^1-5x^0Node*head2=newNode(-5,1);head2->next=newNode(-5,0);Node*head=addPolynomial(head1,head2);printList(head);}
C
// C program to add two polynomials#include<stdio.h>#include<stdlib.h>structNode{intcoeff;intpow;structNode*next;};structNode*createNode(intc,intp);structNode*addPolynomial(structNode*head1,structNode*head2){structNode*dummy=createNode(0,0);// Node to append other nodes to the end // of liststructNode*prev=dummy;structNode*curr1=head1,*curr2=head2;while(curr1!=NULL&&curr2!=NULL){// if curr2.pow > curr1.pow, then // append curr2 to listif(curr1->pow<curr2->pow){prev->next=curr2;prev=curr2;curr2=curr2->next;}// if curr1.pow > curr2.pow, then // append curr2 to listelseif(curr1->pow>curr2->pow){prev->next=curr1;prev=curr1;curr1=curr1->next;}// else, add the sum of curr1->coeff and // curr2->coeff to curr1->coeff, and append// curr1 to the listelse{curr1->coeff=curr1->coeff+curr2->coeff;prev->next=curr1;prev=curr1;curr1=curr1->next;curr2=curr2->next;}}// if curr1 is not null, then append the rest// to the listif(curr1!=NULL){prev->next=curr1;}// if curr2 is not null, then append the rest// to the listif(curr2!=NULL){prev->next=curr2;}returndummy->next;}voidprintList(structNode*head){structNode*curr=head;while(curr!=NULL){printf("%d,%d ",curr->coeff,curr->pow);curr=curr->next;}printf("\n");}structNode*createNode(intc,intp){structNode*newNode=(structNode*)malloc(sizeof(structNode));newNode->coeff=c;newNode->pow=p;newNode->next=NULL;returnnewNode;}intmain(){// 1st polynomial: 5x^2+4x^1+2x^0structNode*head1=createNode(5,2);head1->next=createNode(4,1);head1->next->next=createNode(2,0);// 2nd polynomial: -5x^1-5x^0structNode*head2=createNode(-5,1);head2->next=createNode(-5,0);structNode*head=addPolynomial(head1,head2);printList(head);return0;}
Java
// Java program to add two polynomialsclassNode{intcoeff;intpow;Nodenext;Node(intc,intp){coeff=c;pow=p;next=null;}}classGfG{staticNodeaddPolynomial(Nodehead1,Nodehead2){Nodedummy=newNode(0,0);// Node to append other nodes to the end // of listNodeprev=dummy;Nodecurr1=head1,curr2=head2;while(curr1!=null&&curr2!=null){// if curr2.pow > curr1.pow, then // append curr2 to listif(curr1.pow<curr2.pow){prev.next=curr2;prev=curr2;curr2=curr2.next;}// if curr1.pow > curr2.pow, then // append curr2 to listelseif(curr1.pow>curr2.pow){prev.next=curr1;prev=curr1;curr1=curr1.next;}// else, add the sum of curr1.coeff and // curr2.coeff to curr1.coeff, and append// curr1 to the listelse{curr1.coeff=curr1.coeff+curr2.coeff;prev.next=curr1;prev=curr1;curr1=curr1.next;curr2=curr2.next;}}// if curr1 if not null, then append the rest// to the listif(curr1!=null){prev.next=curr1;}// if curr2 if not null, then append the rest// to the listif(curr2!=null){prev.next=curr2;}returndummy.next;}staticvoidprintList(Nodehead){Nodecurr=head;while(curr!=null){System.out.print(curr.coeff+","+curr.pow+" ");curr=curr.next;}System.out.println();}publicstaticvoidmain(String[]args){// 1st polynomial: 5x^2+4x^1+2x^0Nodehead1=newNode(5,2);head1.next=newNode(4,1);head1.next.next=newNode(2,0);// 2nd polynomial: -5x^1-5x^0Nodehead2=newNode(-5,1);head2.next=newNode(-5,0);Nodehead=addPolynomial(head1,head2);printList(head);}}
Python
# Python program to add two polynomialsclassNode:def__init__(self,c,p):self.coeff=cself.pow=pself.next=Nonedefadd_polynomial(head1,head2):dummy=Node(0,0)# Node to append other nodes to the end # of listprev=dummycurr1,curr2=head1,head2whilecurr1isnotNoneandcurr2isnotNone:# if curr2.pow > curr1.pow, then # append curr2 to listifcurr1.pow<curr2.pow:prev.next=curr2prev=curr2curr2=curr2.next# if curr1.pow > curr2.pow, then # append curr1 to listelifcurr1.pow>curr2.pow:prev.next=curr1prev=curr1curr1=curr1.next# else, add the sum of curr1.coeff and # curr2.coeff to curr1.coeff, and append# curr1 to the listelse:curr1.coeff=curr1.coeff+curr2.coeffprev.next=curr1prev=curr1curr1=curr1.nextcurr2=curr2.next# if curr1 if not None, then append the rest# to the listifcurr1isnotNone:prev.next=curr1# if curr2 if not None, then append the rest# to the listifcurr2isnotNone:prev.next=curr2returndummy.nextdefprint_list(head):curr=headwhilecurrisnotNone:print(f"{curr.coeff},{curr.pow}",end=" ")curr=curr.nextprint()if__name__=="__main__":# 1st polynomial: 5x^2+4x^1+2x^0head1=Node(5,2)head1.next=Node(4,1)head1.next.next=Node(2,0)# 2nd polynomial: -5x^1-5x^0head2=Node(-5,1)head2.next=Node(-5,0)head=add_polynomial(head1,head2)print_list(head)
C#
// C# program to add two polynomialsclassNode{publicintcoeff;publicintpow;publicNodenext;publicNode(intc,intp){coeff=c;pow=p;next=null;}}classGfG{staticNodeAddPolynomial(Nodehead1,Nodehead2){Nodedummy=newNode(0,0);// Node to append other nodes to the end // of listNodeprev=dummy;Nodecurr1=head1,curr2=head2;while(curr1!=null&&curr2!=null){// if curr2.pow > curr1.pow, then // append curr2 to listif(curr1.pow<curr2.pow){prev.next=curr2;prev=curr2;curr2=curr2.next;}// if curr1.pow > curr2.pow, then // append curr1 to listelseif(curr1.pow>curr2.pow){prev.next=curr1;prev=curr1;curr1=curr1.next;}// else, add the sum of curr1.coeff and // curr2.coeff to curr1.coeff, and append// curr1 to the listelse{curr1.coeff=curr1.coeff+curr2.coeff;prev.next=curr1;prev=curr1;curr1=curr1.next;curr2=curr2.next;}}// if curr1 if not null, then append the rest// to the listif(curr1!=null){prev.next=curr1;}// if curr2 if not null, then append the rest// to the listif(curr2!=null){prev.next=curr2;}returndummy.next;}staticvoidPrintList(Nodehead){Nodecurr=head;while(curr!=null){System.Console.Write(curr.coeff+","+curr.pow+" ");curr=curr.next;}System.Console.WriteLine();}staticvoidMain(string[]args){// 1st polynomial: 5x^2+4x^1+2x^0Nodehead1=newNode(5,2);head1.next=newNode(4,1);head1.next.next=newNode(2,0);// 2nd polynomial: -5x^1-5x^0Nodehead2=newNode(-5,1);head2.next=newNode(-5,0);Nodehead=AddPolynomial(head1,head2);PrintList(head);}}
JavaScript
// JavaScript program to add two polynomialsclassNode{constructor(c,p){this.coeff=c;this.pow=p;this.next=null;}}functionaddPolynomial(head1,head2){letdummy=newNode(0,0);// Node to append other nodes to the end // of listletprev=dummy;letcurr1=head1,curr2=head2;while(curr1!==null&&curr2!==null){// if curr2.pow > curr1.pow, then // append curr2 to listif(curr1.pow<curr2.pow){prev.next=curr2;prev=curr2;curr2=curr2.next;}// if curr1.pow > curr2.pow, then // append curr1 to listelseif(curr1.pow>curr2.pow){prev.next=curr1;prev=curr1;curr1=curr1.next;}// else, add the sum of curr1.coeff and // curr2.coeff to curr1.coeff, and append// curr1 to the listelse{curr1.coeff=curr1.coeff+curr2.coeff;prev.next=curr1;prev=curr1;curr1=curr1.next;curr2=curr2.next;}}// if curr1 if not null, then append the rest// to the listif(curr1!==null){prev.next=curr1;}// if curr2 if not null, then append the rest// to the listif(curr2!==null){prev.next=curr2;}returndummy.next;}functionprintList(head){letcurr=head;while(curr!==null){console.log(curr.coeff+","+curr.pow+" ");curr=curr.next;}console.log();}// 1st polynomial: 5x^2+4x^1+2x^0lethead1=newNode(5,2);head1.next=newNode(4,1);head1.next.next=newNode(2,0);// 2nd polynomial: -5x^1-5x^0lethead2=newNode(-5,1);head2.next=newNode(-5,0);lethead=addPolynomial(head1,head2);printList(head);
Output
5,2 -1,1 -3,0
Time Complexity: O(m + n) where m and n are number of nodes in first and second lists respectively. Auxiliary Space: O(1)
We use cookies to ensure you have the best browsing experience on our website. By using our site, you
acknowledge that you have read and understood our
Cookie Policy &
Privacy Policy
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.