6-7-Adding two polynomials using Linked List
6-7-Adding two polynomials using Linked List
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.
Example:
Input:
head1: [[5, 2], [4, 1], [2, 0]]
head2: [[5, 1], [5, 0]]
Output: [[5, 2], [9, 1], [7, 0]]
Explanation:
Input:
head1: [[5, 3], [4, 2], [2, 0]]
head2: [[5, 1], [-5, 0]]
Output: [[5, 3], [4, 2], [5, 1], [-3, 0]]
Explanation: head1 can be represented as 5x^3 + 4x^2 + 2 , head2 can be represented as 5x –
5, add both the polynomials to get 5x^3 + 4x^2 + 5x – 3
Try it on GfG
Practice
Table of Content
[Expected Approach – 1] Using Recursion – O(n+m) Time and O(max(m,n)) Space
[Expected Approach] Using Iterative Method – O(n+m) Time and O(1) 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.
cout<<endl;
}
int main() {
printList(head);
}
Output
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.
class Node {
public:
int coeff;
int pow;
Node* next;
Node(int c, int p) {
coeff = c;
pow = p;
next = nullptr;
}
};
return dummy->next;
}
cout<<endl;
}
int main() {
printList(head);
}
Output
Time Complexity: O(m + n) where m and n are number of nodes in first and second lists respectively.
Auxiliary Space: O(1)