Skip to content
Related Articles
Get the best out of our app
GeeksforGeeks App
Open App
geeksforgeeks
Browser
Continue

Related Articles

Adding two polynomials using Linked List using map

Improve Article
Save Article
Like Article
Improve Article
Save Article
Like Article

Given two polynomial numbers represented by a linked list. Write a function to perform their algebraic sum. Examples:

Input: 1st number = 5x^2 + 4x^1 + 2x^0 2nd number = 5x^1 + 5x^0 Output: 5x^2 + 9x^1 + 7x^0

Approach: The implementation uses map data structure so that all coefficients of same power value are added together and kept in key-value pairs inside a map. Below is the implementation of the above approach: 

CPP




// C++ program for addition of two polynomials
// represented as linked lists
#include <bits/stdc++.h>
using namespace std;
 
// Structure of Node used
struct Node {
 
    // Coefficient of the polynomial
    int coeff;
 
    // Power of the polynomial
    int pow;
    Node* next;
};
 
// Function to create new node
void create_node(int x, int y, struct Node** temp)
{
    struct Node *r, *z;
    z = *temp;
    if (z == NULL) {
        r = (struct Node*)malloc(sizeof(struct Node));
        r->coeff = x;
        r->pow = y;
        *temp = r;
        r->next = (struct Node*)malloc(sizeof(struct Node));
        r = r->next;
        r->next = NULL;
    }
    else {
        r->coeff = x;
        r->pow = y;
        r->next = (struct Node*)malloc(sizeof(struct Node));
        r = r->next;
        r->next = NULL;
    }
}
 
// Display Linked list
void show(struct Node* node)
{
    if (node == NULL)
        return;
    while (node->next != NULL) {
        printf("%dx^%d", node->coeff, node->pow);
        node = node->next;
        if (node->next != NULL)
            printf(" + ");
    }
}
 
/* Function to print the required sum of a
polynomial p1 and p2 as specified in output */
void addPolynomial(Node* p1, Node* p2)
{
    map<int, int> mp;
    Node* temp1 = p1;
    Node* temp2 = p2;
    while (temp1 != NULL) {
 
        // Add coefficients of same power value
        // map contains (powervalue, coeff) pair
        mp[temp1->pow] += temp1->coeff;
        temp1 = temp1->next;
    }
    while (temp2 != NULL) {
        mp[temp2->pow] += temp2->coeff;
        temp2 = temp2->next;
    }
 
    // Started from the end because higher power should
    // come first and there should be "+" symbol in between
    // so iterate up to second element and print last out of
    // the loop.
 
    for (auto it = (mp.rbegin()); it != prev(mp.rend());
         ++it)
        cout << it->second << "x^" << it->first << " + ";
    cout << mp.begin()->second << "x^" << mp.begin()->first;
}
 
// Driver function
int main()
{
    struct Node *poly1 = NULL, *poly2 = NULL, *poly = NULL;
 
    // Create first list of 5x^2 + 4x^1 + 2x^0
    create_node(5, 2, &poly1);
    create_node(4, 1, &poly1);
    create_node(2, 0, &poly1);
 
    // Create second list of 5x^1 + 5x^0
    create_node(5, 1, &poly2);
    create_node(5, 0, &poly2);
 
    printf("1st Number: ");
    show(poly1);
 
    printf("\n2nd Number: ");
    show(poly2);
 
    poly = (struct Node*)malloc(sizeof(struct Node));
 
    printf("\nAdded polynomial: ");
 
    // Function add two polynomial numbers
    addPolynomial(poly1, poly2);
 
    return 0;
}

Java




// Java program for addition of two polynomials
// represented as linked lists
import java.util.*;
 
// Structure of Node used
class Node {
 
    // Coefficient of the polynomial
    int coeff;
 
    // Power of the polynomial
    int pow;
    Node next;
 
    Node(int coeff, int pow) {
        this.coeff = coeff;
        this.pow = pow;
        this.next = null;
    }
}
 
// Display Linked list
class LinkedList {
 
    Node head;
 
    // Function to create new node
    void create_node(int x, int y) {
        Node node = new Node(x, y);
        if (head == null) {
            head = node;
        }
        else {
            Node temp = head;
            while (temp.next != null) {
                temp = temp.next;
            }
            temp.next = node;
        }
    }
 
    void show() {
        Node node = head;
        while (node != null) {
            System.out.print(node.coeff + "x^" + node.pow);
            node = node.next;
            if (node != null) {
                System.out.print(" + ");
            }
        }
    }
}
 
class Main {
 
    // Function to print the required sum of a
    // polynomial p1 and p2 as specified in output
    static void addPolynomial(Node p1, Node p2) {
        Map<Integer, Integer> mp = new TreeMap<>(Collections.reverseOrder());
        Node temp1 = p1;
        Node temp2 = p2;
        while (temp1 != null) {
 
            // Add coefficients of same power value
            // map contains (powervalue, coeff) pair
            mp.put(temp1.pow, mp.getOrDefault(temp1.pow, 0) + temp1.coeff);
            temp1 = temp1.next;
        }
        while (temp2 != null) {
            mp.put(temp2.pow, mp.getOrDefault(temp2.pow, 0) + temp2.coeff);
            temp2 = temp2.next;
        }
 
        // Started from the end because higher power should
        // come first and there should be "+" symbol in between
        // so iterate up to second element and print last out of
        // the loop.
        boolean first = true;
        for (Map.Entry<Integer, Integer> entry : mp.entrySet()) {
            int pow = entry.getKey();
            int coeff = entry.getValue();
            if (first) {
                System.out.print(coeff + "x^" + pow);
                first = false;
            } else {
                System.out.print(" + " + coeff + "x^" + pow);
            }
        }
    }
 
    // Driver function
    public static void main(String[] args) {
        LinkedList poly1 = new LinkedList();
        LinkedList poly2 = new LinkedList();
 
        // Create first list of 5x^2 + 4x^1 + 2x^0
        poly1.create_node(5, 2);
        poly1.create_node(4, 1);
        poly1.create_node(2, 0);
 
        // Create second list of 5x^1 + 5x^0
        poly2.create_node(5, 1);
        poly2.create_node(5, 0);
 
        System.out.print("1st Number: ");
        poly1.show();
 
        System.out.print("\n2nd Number: ");
        poly2.show();
 
        System.out.print("\nAdded polynomial: ");
 
        // Function add two polynomial numbers
        addPolynomial(poly1.head, poly2.head);
    }
}
// This code is contributed by Prajwal Kandekar

Python3




# Python program for addition of two polynomials
# represented as linked lists
 
# Structure of Node used
class Node:
    # Coefficient of the polynomial
    def __init__(self, coeff, pow):
        self.coeff = coeff
        # Power of the polynomial
        self.pow = pow
        self.next = None
 
# Function to create new node
def create_node(x, y):
    r = Node(x, y)
    r.next = None
    return r
 
# Display Linked list
def show(node):
    if node is None:
        return
    while node.next is not None:
        print(f"{node.coeff}x^{node.pow}", end="")
        print(" + ", end="")
        node = node.next
        if node.next is not None:
            print(" ", end="")
    print(f"{node.coeff}x^{node.pow}")
 
# Function to print the required sum of a
# polynomial p1 and p2 as specified in output
def addPolynomial(p1, p2):
    mp = {}
    temp1 = p1
    temp2 = p2
    while temp1 is not None:
        # Add coefficients of same power value
        # map contains (powervalue, coeff) pair
        mp[temp1.pow] = mp.get(temp1.pow, 0) + temp1.coeff
        temp1 = temp1.next
    while temp2 is not None:
        mp[temp2.pow] = mp.get(temp2.pow, 0) + temp2.coeff
        temp2 = temp2.next
 
    # Started from the end because higher power should
    # come first and there should be "+" symbol in between
    # so iterate up to second element and print last out of
    # the loop.
    for power in sorted(mp.keys(), reverse=True):
        print(f"{mp[power]}x^{power}", end="")
        if power != sorted(mp.keys(), reverse=True)[-1]:
            print(" + ", end="")
 
# Driver function
if __name__ == "__main__":
    poly1 = None
    poly2 = None
    poly = None
 
    # Create first list of 5x^2 + 4x^1 + 2x^0
    poly1 = create_node(5, 2)
    poly1.next = create_node(4, 1)
    poly1.next.next = create_node(2, 0)
 
    # Create second list of 5x^1 + 5x^0
    poly2 = create_node(5, 1)
    poly2.next = create_node(5, 0)
 
    print("1st Number: ", end="")
    show(poly1)
 
    print("2nd Number: ", end="")
    show(poly2)
 
    print("Added polynomial: ", end="")
 
    # Function to add two polynomial numbers
    addPolynomial(poly1, poly2)

Time Complexity: O((m + n)log(m+n)) where m and n are numbers of nodes in first and second lists respectively and we are using a map for adding the coefficients extra log(m+n) factor is added.


My Personal Notes arrow_drop_up
Last Updated : 17 Mar, 2023
Like Article
Save Article
Similar Reads
Related Tutorials