Lecture 4
Lecture 4
Polynomial Multiplications
• Input: two linked lists representing two polynomials
• Perform the multiplication of the two polynomials and return the
output as a linked list
• Let P(x) = x² − 5x + 9 and Q(x) = x3 − 10x2 + 9x + 1
• Find the product P(x)*Q(x).
P(x)*Q(x) = (x² − 5x + 9) * (x3 − 10x2 + 9x + 1)
Every term of P(x) will be multiplied to Q(x) :
P(x)*Q(x) = x² (x3 − 10x2 + 9x + 1) - 5x(x3 − 10x2 + 9x + 1) + 9(x3−10x2+ 9x +
1)
P(x)*Q(x) =x5 - 10x4 + 9x3 + x2 - 5x4+50x3 -45x2 - 5x + 9x3 - 90x2 + 81x + 9
=x5 -15x4 +68x3 -134x2 +76x +9
Algorithm
• Define two pointers ptr1 and ptr2, which points to head1 and head2, respectively. These pointers will
be used to iterate over the two lists.
• Define a new node head3 which points to the head node of the resulting product polynomial.
• Create a new node with the coefficient and exponent found above and append it to the list pointed by head3.
• Update ptr2 to point to the next node in the second polynomial and repeat the above steps
till ptr2 becomes NULL.
• Similarly, after each complete pass over the second polynomial reset ptr2 to point to head2 and update ptr1 to
point to the next node in the first polynomial
• Traverse result list and add nodes with same power and remove duplicate
Polynomial Division
• 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.
Set operations using linked list
• Given two Linked Lists, create union and intersection lists that contain
union and intersection of the elements present in the given lists
• Input:
List1: 10->15->4->20
List2: 8->4->2->10
• Output:
Intersection List: 4->10
Union List: 2->8->20->4->15->10
Union and Intersection
• Intersection (list1, list2)
• Initialize the result list as NULL.
• Traverse list1 and look for every element in list2, if the element is present in
list2, then add the element to the result.
• Union (list1, list2):
• Initialize the result list as NULL. Traverse list1 and add all of its elements to
the result.
• Traverse list2. If an element of list2 is already present in the result then do not
insert it to the result, otherwise insert.