Polynomial Division using Linked List
Given two polynomials P1 and P2 in the form of a singly linked list respectively, the task is to print the quotient and remainder expressions in the form of a singly linked list, obtained by dividing the polynomials P1 by P2.
Note: Assume the polynomial is expressed as the higher power of x to the lower power of x(i.e., 0).
Input: P1 = 5 -> 4 -> 2, P2 = 5 -> 5
Quotient = 1 -> 0.2
Remainder = 3
Input: P1 = 3 -> 5 -> 2, P2 = 2 -> 1
Quotient = 1.5 -> 1.75
Remainder = 0.25
Approach: Follow the steps below to solve the problem:
- Create two singly linked lists, quotient, and the remainder, where each node will consist of the coefficient of power of x, and a pointer to the next node.
- While the degree of the remainder is less than the degree of the divisor do the following:
- Subtract the power of the leading term of the dividend by that of the divisor and store in power.
- Divide the coefficient of the leading term of the dividend by the divisor and store in the variable coefficient.
- Create a new node N from the terms formed in step 1 and step 2 and insert N in the quotient list.
- Multiply N with the divisor and subtract the dividend from the obtained result.
- After the above steps, print the quotient and the remainder list.
Below is the implementation of the above approach:
Quotient: 1x^1 - 0.2 Remainder: 3
Time Complexity: O(M + N)
Auxiliary Space: O(M + N)