VOOZH about

URL: https://www.geeksforgeeks.org/dsa/adding-two-polynomials-using-linked-list/

⇱ Adding two polynomials using Linked List - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Adding two polynomials using Linked List

Last Updated : 13 Sep, 2024

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:

👁 33_1


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

[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:


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:


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)

Comment