Open In App

Adding two polynomials using Linked List

Improve
Improve
Like Article
Like
Save
Share
Report

Given two polynomial numbers represented by a linked list. Write a function that add these lists means add the coefficients who have same variable powers.
Example:  

Input:
     1st number = 5x2 + 4x1 + 2x0
     2nd number = -5x1 - 5x0
Output:
        5x2-1x1-3x0
Input:
     1st number = 5x3 + 4x2 + 2x0
     2nd number = 5x^1 - 5x^0
Output:
        5x3 + 4x2 + 5x1 - 3x0

Addition-of-two-polynomial

Recommended Practice

Implementation:

CPP




// C++ program for addition of two polynomials
// using Linked Lists
#include <bits/stdc++.h>
using namespace std;
  
// Node structure containing power and coefficient of
// variable
struct Node {
    int coeff;
    int pow;
    struct 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;
    }
}
  
// Function Adding two polynomial numbers
void polyadd(struct Node* poly1, struct Node* poly2,
             struct Node* poly)
{
    while (poly1->next && poly2->next) {
        // If power of 1st polynomial is greater then 2nd,
        // then store 1st as it is and move its pointer
        if (poly1->pow > poly2->pow) {
            poly->pow = poly1->pow;
            poly->coeff = poly1->coeff;
            poly1 = poly1->next;
        }
  
        // If power of 2nd polynomial is greater then 1st,
        // then store 2nd as it is and move its pointer
        else if (poly1->pow < poly2->pow) {
            poly->pow = poly2->pow;
            poly->coeff = poly2->coeff;
            poly2 = poly2->next;
        }
  
        // If power of both polynomial numbers is same then
        // add their coefficients
        else {
            poly->pow = poly1->pow;
            poly->coeff = poly1->coeff + poly2->coeff;
            poly1 = poly1->next;
            poly2 = poly2->next;
        }
  
        // Dynamically create new node
        poly->next
            = (struct Node*)malloc(sizeof(struct Node));
        poly = poly->next;
        poly->next = NULL;
    }
    while (poly1->next || poly2->next) {
        if (poly1->next) {
            poly->pow = poly1->pow;
            poly->coeff = poly1->coeff;
            poly1 = poly1->next;
        }
        if (poly2->next) {
            poly->pow = poly2->pow;
            poly->coeff = poly2->coeff;
            poly2 = poly2->next;
        }
        poly->next
            = (struct Node*)malloc(sizeof(struct Node));
        poly = poly->next;
        poly->next = NULL;
    }
}
  
// Display Linked list
void show(struct Node* node)
{
    while (node->next != NULL) {
        printf("%dx^%d", node->coeff, node->pow);
        node = node->next;
        if (node->coeff >= 0) {
            if (node->next != NULL)
                printf("+");
        }
    }
}
  
// Driver code
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));
  
    // Function add two polynomial numbers
    polyadd(poly1, poly2, poly);
  
    // Display resultant List
    printf("\nAdded polynomial: ");
    show(poly);
  
    return 0;
}


Java




import java.io.*;
import java.util.Scanner;
  
class Polynomial {
    public static Node addPolynomial(Node p1, Node p2)
    {
  
        Node a = p1, b = p2, newHead = new Node(0, 0),
             c = newHead;
  
        while (a != null || b != null) {
  
            if (a == null) {
                c.next = b;
                break;
            }
            else if (b == null) {
                c.next = a;
                break;
            }
  
            else if (a.pow == b.pow) {
                c.next = new Node(a.coeff + b.coeff, a.pow);
  
                a = a.next;
                b = b.next;
            }
  
            else if (a.pow > b.pow) {
                c.next = new Node(a.coeff, a.pow);
  
                a = a.next;
            }
  
            else if (a.pow < b.pow) {
                c.next = new Node(b.coeff, b.pow);
  
                b = b.next;
            }
  
            c = c.next;
        }
  
        return newHead.next;
    }
}
  
// Utilities for Linked List Nodes
class Node {
    int coeff;
    int pow;
    Node next;
    Node(int a, int b)
    {
        coeff = a;
        pow = b;
        next = null;
    }
}
  
//Linked List main class
class LinkedList {
    
    public static void main(String args[])
    {
  
        Node start1 = null, cur1 = null, start2 = null,
             cur2 = null;
  
        int[] list1_coeff = { 5, 4, 2 };
        int[] list1_pow = { 2, 1, 0 };
        int n = list1_coeff.length;
  
        int i = 0;
        while (n-- > 0) {
            int a = list1_coeff[i];
            int b = list1_pow[i];
  
            Node ptr = new Node(a, b);
  
            if (start1 == null) {
                start1 = ptr;
                cur1 = ptr;
            }
  
            else {
                cur1.next = ptr;
                cur1 = ptr;
            }
  
            i++;
        }
  
        int[] list2_coeff = { -5, -5 };
        int[] list2_pow = { 1, 0 };
        n = list2_coeff.length;
  
        i = 0;
        while (n-- > 0) {
            int a = list2_coeff[i];
            int b = list2_pow[i];
  
            Node ptr = new Node(a, b);
  
            if (start2 == null) {
                start2 = ptr;
                cur2 = ptr;
            }
  
            else {
                cur2.next = ptr;
                cur2 = ptr;
            }
  
            i++;
        }
  
        Polynomial obj = new Polynomial();
  
        Node sum = obj.addPolynomial(start1, start2);
  
        Node trav = sum;
        while (trav != null) {
            System.out.print(trav.coeff + "x^" + trav.pow);
            if (trav.next != null)
                System.out.print(" + ");
            trav = trav.next;
        }
        System.out.println();
    }
}


Python3




# Python3 program to implement the approach
  
# Utilities for Linked List Nodes
class Node:
      
    # Constructor to initialize a node
    def __init__(self, a, b):
        self.coeff = a;
        self.pow = b;
        self.next = None;
  
# Polynomial Class definition
class Polynomial:
      
    # Method to add two polynomials
    def addPolynomial(self, p1, p2):
  
        a = p1
        b = p2
        newHead = Node(0, 0)
        c = newHead;
  
        while (a != None or b != None):
  
            if (a == None):
                c.next = b;
                break
              
            elif (b == None):
                c.next = a;
                break;
              
  
            elif (a.pow == b.pow):
                c.next = Node(a.coeff + b.coeff, a.pow);
  
                a = a.next;
                b = b.next;
              
  
            elif (a.pow > b.pow):
                c.next = Node(a.coeff, a.pow);
  
                a = a.next;
              
  
            elif (a.pow < b.pow):
                c.next = Node(b.coeff, b.pow);
  
                b = b.next;
              
  
            c = c.next;
  
        return newHead.next;
      
# Driver Code
start1 = None
cur1 = None
start2 = None
cur2 = None;
  
list1_coeff = [ 5, 4, 2 ];
list1_pow = [ 2, 1, 0 ];
n = len(list1_coeff);
  
i = 0;
while (n > 0):
    a = list1_coeff[i];
    b = list1_pow[i];
  
    ptr =  Node(a, b);
  
    if (start1 == None):
        start1 = ptr;
        cur1 = ptr;
      
    else:
        cur1.next = ptr;
        cur1 = ptr;
  
    i += 1
    n -= 1
  
list2_coeff = [ -5, -5 ];
list2_pow = [ 1, 0 ];
n = len(list2_coeff);
  
i = 0;
while (n > 0):
    a = list2_coeff[i];
    b = list2_pow[i];
  
    ptr = Node(a, b);
  
    if (start2 == None):
        start2 = ptr;
        cur2 = ptr;
  
    else :
        cur2.next = ptr;
        cur2 = ptr;
      
    n -= 1
    i += 1
  
  
obj = Polynomial();
  
sum = obj.addPolynomial(start1, start2);
  
trav = sum;
  
# Displaying the result
while (trav != None):
    print(trav.coeff, "x^", trav.pow, sep = "", end = "");
    if (trav.next != None):
        print(" + ", end = "");
    trav = trav.next;
  
print()
  
# This code is contributed by phasing17


C#




// C# code to implement the approach
using System;
  
// Utilities for Linked List Nodes
class Node {
    public int coeff;
    public int pow;
    public Node next;
    public Node(int a, int b)
    {
        coeff = a;
        pow = b;
        next = null;
    }
}
  
  
// Polynomial class 
class Polynomial {
    public  Node addPolynomial(Node p1, Node p2)
    {
  
        Node a = p1, b = p2, newHead = new Node(0, 0),
             c = newHead;
  
        while (a != null || b != null) {
  
            if (a == null) {
                c.next = b;
                break;
            }
            else if (b == null) {
                c.next = a;
                break;
            }
  
            else if (a.pow == b.pow) {
                c.next = new Node(a.coeff + b.coeff, a.pow);
  
                a = a.next;
                b = b.next;
            }
  
            else if (a.pow > b.pow) {
                c.next = new Node(a.coeff, a.pow);
  
                a = a.next;
            }
  
            else if (a.pow < b.pow) {
                c.next = new Node(b.coeff, b.pow);
  
                b = b.next;
            }
  
            c = c.next;
        }
  
        return newHead.next;
    }
}
  
  
//Linked List main class
class LinkedList {
    
    public static void Main(string[] args)
    {
  
        Node start1 = null, cur1 = null, start2 = null,
             cur2 = null;
  
        int[] list1_coeff = { 5, 4, 2 };
        int[] list1_pow = { 2, 1, 0 };
        int n = list1_coeff.Length;
  
        int i = 0;
        while (n-- > 0) {
            int a = list1_coeff[i];
            int b = list1_pow[i];
  
            Node ptr = new Node(a, b);
  
            if (start1 == null) {
                start1 = ptr;
                cur1 = ptr;
            }
  
            else {
                cur1.next = ptr;
                cur1 = ptr;
            }
  
            i++;
        }
  
        int[] list2_coeff = { -5, -5 };
        int[] list2_pow = { 1, 0 };
        n = list2_coeff.Length;
  
        i = 0;
        while (n-- > 0) {
            int a = list2_coeff[i];
            int b = list2_pow[i];
  
            Node ptr = new Node(a, b);
  
            if (start2 == null) {
                start2 = ptr;
                cur2 = ptr;
            }
  
            else {
                cur2.next = ptr;
                cur2 = ptr;
            }
  
            i++;
        }
  
        Polynomial obj = new Polynomial();
  
        Node sum = obj.addPolynomial(start1, start2);
  
        Node trav = sum;
        while (trav != null) {
            Console.Write(trav.coeff + "x^" + trav.pow);
            if (trav.next != null)
                Console.Write(" + ");
            trav = trav.next;
        }
        Console.WriteLine();
    }
}
  
  
// This code is contributed by phasing17


Javascript




// JavaScript program to implement the approach
  
  
// Polynomial Class definition
class Polynomial {
      
    // Method to add two polynomials
    addPolynomial(p1, p2)
    {
  
        let a = p1, b = p2, newHead = new Node(0, 0),
            c = newHead;
  
        while (a != null || b != null) {
  
            if (a == null) {
                c.next = b;
                break;
            }
            else if (b == null) {
                c.next = a;
                break;
            }
  
            else if (a.pow == b.pow) {
                c.next = new Node(a.coeff + b.coeff, a.pow);
  
                a = a.next;
                b = b.next;
            }
  
            else if (a.pow > b.pow) {
                c.next = new Node(a.coeff, a.pow);
  
                a = a.next;
            }
  
            else if (a.pow < b.pow) {
                c.next = new Node(b.coeff, b.pow);
  
                b = b.next;
            }
  
            c = c.next;
        }
  
        return newHead.next;
    }
}
  
// Utilities for Linked List Nodes
class Node {
      
    // Constructor to initialize a node
    constructor(a, b)
    {
        this.coeff = a;
        this.pow = b;
        this.next = null;
    }
  
}
  
// Driver Code
  
let start1
    = null,
    cur1 = null, start2 = null, cur2 = null;
  
let list1_coeff = [ 5, 4, 2 ];
let list1_pow = [ 2, 1, 0 ];
let n = list1_coeff.length;
  
let i = 0;
while (n-- > 0) {
    let a = list1_coeff[i];
    let b = list1_pow[i];
  
    let ptr = new Node(a, b);
  
    if (start1 == null) {
        start1 = ptr;
        cur1 = ptr;
    }
  
    else {
        cur1.next = ptr;
        cur1 = ptr;
    }
  
    i++;
}
  
let list2_coeff = [ -5, -5 ];
let list2_pow = [ 1, 0 ];
n = list2_coeff.length;
  
i = 0;
while (n-- > 0) {
    let a = list2_coeff[i];
    let b = list2_pow[i];
  
    let ptr = new Node(a, b);
  
    if (start2 == null) {
        start2 = ptr;
        cur2 = ptr;
    }
  
    else {
        cur2.next = ptr;
        cur2 = ptr;
    }
  
    i++;
}
  
let obj = new Polynomial();
  
let sum = obj.addPolynomial(start1, start2);
  
let trav = sum;
  
  
// Displaying the result
while (trav != null) {
    process.stdout.write(trav.coeff + "x^" + trav.pow);
    if (trav.next != null)
        process.stdout.write(" + ");
    trav = trav.next;
}
console.log();
  
  
// This code is contributed by phasing17


Output

1st Number: 5x^2+4x^1+2x^0
2nd Number: -5x^1-5x^0
Added polynomial: 5x^2-1x^1-3x^0

Time Complexity: O(m + n) where m and n are number of nodes in first and second lists respectively.

Space Complexity: O(m+n), since we create a new linked list of size m + n to store the result of the addition of the two polynomials.

Simple and concise version of the above approach:

We will maintain a prev pointer that will point to the last node of resultant linked list. We will be modifying the same given nodes rather than creating new ones .The below code will provide you with more insight. 

Thank you Nakshatra Chhillar for suggesting this simplification and contributing the code : 

Implementation:

C++




#include <bits/stdc++.h>
using namespace std;
  
/* Link list Node */
struct Node {
    int coeff;
    int pow;
    struct Node* next;
  
    Node(int c, int p)
    {
        coeff = c;
        pow = p;
        next = NULL;
    }
};
void append(struct Node** head_ref, struct Node** tail_ref,
            int new_data, int new_data1)
{
    struct Node* new_node = new Node(new_data, new_data1);
  
    if (*head_ref == NULL)
        *head_ref = new_node;
    else
        (*tail_ref)->next = new_node;
    *tail_ref = new_node;
}
void printList(struct Node* head)
{
    struct Node* temp = head;
  
    while (temp != NULL) {
        printf("%d %d ", temp->coeff, temp->pow);
        temp = temp->next;
    }
}
Node* addPolynomial(Node* p1, Node* p2);
void create_node(int x, int y, struct Node** temp)
{
    struct Node *r, *z;
    z = *temp;
    if (z == NULL) {
        r = new Node(x, y);
        *temp = r;
        r->next = NULL;
    }
    else {
        r->next = new Node(x, y);
        r = r->next;
        r->next = NULL;
    }
}
  
/* Structure of Node used
struct Node
{
    int coeff;
    int pow;
    struct Node* next;
  
    Node(int c, int p){
        coeff = c;
        pow = p;
        next = NULL;
    }
  
};
*/
// 1st Number: 5x^2+4x^1+2x^0
// 2nd Number: -5x^1-5x^0
class Solution {
public:
    /* The below method print the required sum of polynomial
    p1 and p2 as specified in output  */
    Node* addPolynomial(Node* p1, Node* p2)
    {
        Node* res = new Node(
            0, 0); // dummy node ...head of resultant list
        Node* prev
            = res; // pointer to last node of resultant list
        // like Merge procedure :
        while (p1 != NULL and p2 != NULL) {
            if (p1->pow < p2->pow) {
                prev->next = p2;
                prev = p2;
                p2 = p2->next;
            }
            else if (p1->pow > p2->pow) {
                prev->next = p1;
                prev = p1;
                p1 = p1->next;
            }
            else {
                p1->coeff = p1->coeff + p2->coeff;
                prev->next = p1;
                prev = p1;
                p1 = p1->next;
                p2 = p2->next;
            }
        }
        if (p1 != NULL) {
            prev->next = p1;
        }
        if (p2 != NULL) {
            prev->next = p2;
        }
        return res->next;
    }
};
  
int main()
{
    struct Node *poly1 = NULL, *poly2 = NULL, *poly = NULL;
    struct Node *tail1 = NULL, *tail2 = NULL;
    // 1st Number: 5x^2+4x^1+2x^0
    append(&poly1, &tail1, 5, 2);
    append(&poly1, &tail1, 4, 1);
    append(&poly1, &tail1, 2, 0);
    // 2nd Number: -5x^1-5x^0
    append(&poly2, &tail2, -5, 1);
    append(&poly2, &tail2, -5, 0);
    Solution obj;
    Node* sum = obj.addPolynomial(poly1, poly2);
    for (Node* ptr = sum; ptr; ptr = ptr->next) {
        // printing polynomial
        cout << ptr->coeff << "x^" << ptr->pow;
        if (ptr->next)
            cout << " + ";
    }
    cout << endl;
}
// contributed by Nakshatra Chhillar


Java




import java.util.*;
  
// 1st Number: 5x^2+4x^1+2x^0
// 2nd Number: -5x^1-5x^0
public class Solution {
  
    // Driver code
    public static void main(String args[])
    {
        // 1st Number: 5x^2+4x^1+2x^0
        Node poly1 = new Node(5, 2);
        append(poly1, 4, 1);
        append(poly1, 2, 0);
  
        // 2nd Number: -5x^1-5x^0
        Node poly2 = new Node(-5, 1);
        append(poly2, -5, 0);
  
        Node sum = addPolynomial(poly1, poly2);
        for (Node ptr = sum; ptr != null; ptr = ptr.next) {
            // printing polynomial
            System.out.print(ptr.coeff + "x^"
                             + ptr.pow);
            if (ptr.next != null)
                System.out.print(" + ");
        }
        System.out.println();
    }
  
    // insert in linked list
    public static void append(Node head, int coeff,
                              int power)
    {
        Node new_node = new Node(coeff, power);
        while (head.next != null) {
            head = head.next;
        }
        head.next = new_node;
    }
  
    /* The below method print the required sum of polynomial
    p1 and p2 as specified in output  */
    public static Node addPolynomial(Node p1, Node p2)
    {
        Node res = new Node(
            0, 0); // dummy node ...head of resultant list
        Node prev
            = res; // pointer to last node of resultant list
        while (p1 != null && p2 != null) {
            if (p1.pow < p2.pow) {
                prev.next = p2;
                prev = p2;
                p2 = p2.next;
            }
            else if (p1.pow > p2.pow) {
                prev.next = p1;
                prev = p1;
                p1 = p1.next;
            }
            else {
                p1.coeff = p1.coeff + p2.coeff;
                prev.next = p1;
                prev = p1;
                p1 = p1.next;
                p2 = p2.next;
            }
        }
        if (p1 != null) {
            prev.next = p1;
        }
        else if (p2 != null) {
            prev.next = p2;
        }
        return res.next;
    }
}
  
/* Link list Node */
class Node {
    public int coeff;
    public int pow;
    public Node next;
  
    public Node(int c, int p)
    {
        this.coeff = c;
        this.pow = p;
        this.next = null;
    }
}
  
// This code is contributed by Tapesh(tapeshdua420)


Python3




# 1st Number: 5x^2+4x^1+2x^0
# 2nd Number: -5x^1-5x^0
  
# Link list Node
class Node:
    def __init__(self, c, p):
        self.coeff = c
        self.pow = p
        self.next = None
  
# insert in linked list
def append(head, coeff, power):
    new_node = Node(coeff, power)
  
    while head.next != None:
        head = head.next
    head.next = new_node
  
# The below method print the required sum of polynomial p1 and p2 as specified in output
def addPolynomial(p1, p2):
    res = Node(0, 0# dummy node ...head of resultant list
    prev = res  # pointer to last node of resultant list
  
    while p1 != None and p2 != None:
        if p1.pow < p2.pow:
            prev.next = p2
            prev = p2
            p2 = p2.next
        elif p1.pow > p2.pow:
            prev.next = p1
            prev = p1
            p1 = p1.next
        else:
            p1.coeff += p2.coeff
            prev.next = p1
            prev = p1
            p1 = p1.next
            p2 = p2.next
  
    if (p1 != None):
        prev.next = p1
  
    if (p2 != None):
        prev.next = p2
  
    return res.next
  
  
# Driver code
if __name__ == '__main__':
  
    # 1st Number: 5x^2+4x^1+2x^0
    poly1 = Node(5, 2)
    append(poly1, 4, 1)
    append(poly1, 2, 0)
  
    # 2nd Number: -5x^1-5x^0
    poly2 = Node(-5, 1)
    append(poly2, -5, 0)
  
    sum = addPolynomial(poly1, poly2)
  
    ptr = sum
    while ptr != None:
        # printing polynomial
        print(ptr.coeff, 'x^', ptr.pow, end="")
        if ptr.next != None:
            print(" + ", end="")
        ptr = ptr.next
    print()
  
# This code is contributed by Tapesh(tapeshdua420)


C#




using System;
  
/* linked lis node */
class Node {
    public int coeff;
    public int pow;
    public Node next;
    public Node(int c, int p)
    {
        this.coeff = c;
        this.pow = p;
        this.next = null;
    }
}
  
// 1st Number: 5x^2+4x^1+2x^0
// 2nd Number: -5x^1-5x^0
class Program {
  
    // Driver Code
    public static void Main(string[] args)
    {
        // 1st Number: 5x^2+4x^1+2x^0
        Node poly1 = new Node(5, 2);
        append(poly1, 4, 1);
        append(poly1, 2, 0);
  
        // 2nd Number: -5x^1-5x^0
        Node poly2 = new Node(-5, 1);
        append(poly2, -5, 0);
  
        Node sum = addPolynomial(poly1, poly2);
        for (Node ptr = sum; ptr != null; ptr = ptr.next) {
            // printing polynomial
            Console.Write(ptr.coeff + "x^" + ptr.pow);
            if (ptr.next != null)
                Console.Write(" + ");
        }
        Console.ReadKey();
    }
    // insert in linked list
    public static void append(Node head, int coeff,
                              int power)
    {
        Node new_node = new Node(coeff, power);
        while (head.next != null) {
            head = head.next;
        }
        head.next = new_node;
    }
  
    /* The below method print the required sum of polynomial
     * p1 and p2 as specified in output */
    public static Node addPolynomial(Node p1, Node p2)
    {
        Node res = new Node(
            0, 0); // dummy node ...head of resultant list
        Node prev
            = res; // pointer to last node of resultant list
        while (p1 != null && p2 != null) {
            if (p1.pow < p2.pow) {
                prev.next = p2;
                prev = p2;
                p2 = p2.next;
            }
            else if (p1.pow > p2.pow) {
                prev.next = p1;
                prev = p1;
                p1 = p1.next;
            }
            else {
                p1.coeff += p2.coeff;
                prev.next = p1;
                prev = p1;
                p1 = p1.next;
                p2 = p2.next;
            }
        }
        if (p1 != null) {
            prev.next = p1;
        }
        else if (p2 != null) {
            prev.next = p2;
        }
        return res.next;
    }
}
  
// This code is contributed by Tapesh(tapeshdua420)


Javascript




// 1st Number: 5x^2+4x^1+2x^0
// 2nd Number: -5x^1-5x^0
 
// Link list Node
class Node {
    constructor(c, p) {
        this.coeff = c;
        this.pow = p;
        this.next = null;
    }
}
 
// insert in linked list
function append(head, coeff, power) {
    let new_node = new Node(coeff, power);
    while (head.next != null) {
        head = head.next;
    }
    head.next = new_node;
}
 
// The below method print the required sum of polynomial p1 and p2 as specified in output
function addPolynomial(p1, p2) {
    let res = new Node(0, 0); // dummy node ...head of resultant list 
    let prev = res; // pointer to last node of resultant list 
    while (p1 != null && p2 != null) {
        if (p1.pow < p2.pow) {
            prev.next = p2;
            prev = p2;
            p2 = p2.next;
        } else if (p1.pow > p2.pow) {
            prev.next = p1;
            prev = p1;
            p1 = p1.next;
        } else {
            p1.coeff += p2.coeff;
            prev.next = p1;
            prev = p1;
            p1 = p1.next;
            p2 = p2.next;
        }
    }
 
    if (p1 != null) {
        prev.next = p1;
    }
    if (p2 != null) {
        prev.next = p2;
    }
    return res.next;
}
 
// Driver code
 
// 1st Number: 5x^2+4x^1+2x^0
poly1 = new Node(5, 2)
append(poly1, 4, 1)
append(poly1, 2, 0)
 
// 2nd Number: -5x^1-5x^0
poly2 = new Node(-5, 1)
append(poly2, -5, 0)
 
sum = addPolynomial(poly1, poly2)
 
ptr = sum;
while (ptr != null){
    // printing polynomial
   process.stdout.write(ptr.coeff + 'x^' + ptr.pow);
    if(ptr.next != null){
        process.stdout.write(" + ")
    }
    ptr = ptr.next;
}
console.log();
 
// This code is contributed by Tapesh(tapeshdua420).


Output

5x^2 + -1x^1 + -3x^0

Time Complexity: O(m + n) where m and n are number of nodes in first and second lists respectively.

Space Complexity: O(1) no extra nodes have been created

 

Recursive Method :

Algorithm :

  1. If both the numbers are null then return
  2. else if compare the power, if same then  add the coefficients and recursively call  addPolynomials on the next elements of both the numbers.
  3. else if the power of first number is greater then print the current element of first number and recursively call addPolynomial on the next element of the first number and current element of the second number.
  4. else print the current element of the second number and recursively call addPolynomial on the current element of first number and next element of second number.

Implementation:

C++




// Program to add two polynomials represented
// in linkedlist using recursion
#include<iostream>
using namespace std;
  
class Node{
public:
  int coeff,power;
  Node *next;
  Node(int coeff, int power){
    this->coeff = coeff;
    this->power = power;
    this->next = NULL;
  }
};
  
void addPolynomials(Node *head1, Node *head2){
  
  if(head1==NULL && head2==NULL)
    return;
  else if(head1->power == head2->power){
    cout<<" "<<head1->coeff +  head2->coeff<<"x^"<<head1->power<<" ";
    addPolynomials(head1->next,head2->next);
  }
  else if(head1->power > head2->power){
    cout<<" "<<head1->coeff<<"x^"<<head1->power<<" ";
    addPolynomials(head1->next,head2);
  }
  else{
    cout<<" "<<head2->coeff<<"x^"<<head2->power<<" ";
    addPolynomials(head1,head2->next);
  }
}
  
void insert(Node *head, int coeff, int power){
  Node *new_node = new Node(coeff,power);
  while(head->next!=NULL){
    head = head->next;
  }
  head->next = new_node;
}
  
void printList(Node *head){
  cout<<"Linked List"<<endl;
  while(head!=NULL){
    cout<<" "<<head->coeff<<"x"<<"^"<<head->power;
    head = head->next;
  }
}
  
int main(){
  
  Node *head=new Node(5,2);
  insert(head,4,1);
  Node *head2 = new Node(6,2);
  insert(head2,4,1);
  printList(head);
  cout<<endl;
  printList(head2);
  cout<<endl<<"Addition:"<<endl;
  addPolynomials(head,head2);
  
  
  return 0;
}
  
//This code is contributed by Akshita Patel


Java




// Program to add two polynomials represented
// in linkedlist using recursion
  
import java.util.*;
  
public class Polynomial {
  
    public static void main(String[] args)
    {
        Node head = new Node(5, 2);
        insert(head, 4, 1);
        Node head2 = new Node(6, 2);
        insert(head2, 4, 1);
        printList(head);
        System.out.println();
        printList(head2);
        System.out.println("\nAddition:");
        addPolynomials(head, head2);
    }
  
    public static void addPolynomials(Node head1,
                                      Node head2)
    {
        if (head1 == null && head2 == null)
            return;
        else if (head1.power == head2.power) {
            System.out.print(" " + (head1.coeff + head2.coeff)
                             + "x^" + head1.power + " ");
            addPolynomials(head1.next, head2.next);
        }
        else if (head1.power > head2.power) {
            System.out.print(" " + head1.coeff + "x^"
                             + head1.power + " ");
            addPolynomials(head1.next, head2);
        }
        else {
            System.out.print(" " + head2.coeff + "x^"
                             + head2.power + " ");
            addPolynomials(head1, head2.next);
        }
    }
    public static void insert(Node head, int coeff,
                              int power)
    {
        Node new_node = new Node(coeff, power);
        while (head.next != null) {
            head = head.next;
        }
        head.next = new_node;
    }
    public static void printList(Node head)
    {
        System.out.println("Linked List");
        while (head != null) {
            System.out.print(" " + head.coeff + "x"
                             + "^" + head.power);
            head = head.next;
        }
    }
}
  
class Node {
    public int coeff, power;
    public Node next;
    public Node(int coeff, int power)
    {
        this.coeff = coeff;
        this.power = power;
        this.next = null;
    }
}
  
// This code is contributed by Tapesh(tapeshdua420)


Python3




# Python3 Program to add two polynomials
# represented in linkedlist using recursion
class Node:
    def __init__(self, coeff, power):
        self.coeff = coeff
        self.power = power
        self.next = None
  
def addPolynomials(head1, head2):
    if(head1 == None and head2 == None):
        return
    elif(head1.power == head2.power):
        print(f"{head1.coeff + head2.coeff}x^{head1.power}", end=" ")
        addPolynomials(head1.next, head2.next)
  
    elif(head1.power > head2.power):
        print(f"{head1.coeff}x^{head1.power}", end=" ")
        addPolynomials(head1.next, head2)
  
    else:
        print(f"{head2.coeff}x^{head2.power} ", end=" ")
        addPolynomials(head1, head2.next)
  
  
def insert(head, coeff, power):
    new_node = Node(coeff, power)
    while(head.next != None):
        head = head.next
  
    head.next = new_node
  
  
def printList(head):
    print("Linked List")
    while(head != None):
        print(f'{head.coeff}x^{head.power}', end=" ")
        head = head.next
  
# Driver code
head = Node(5, 2)
insert(head, 4, 1)
head2 = Node(6, 2)
insert(head2, 4, 1)
printList(head)
print()
printList(head2)
print()
print("Addition:")
addPolynomials(head, head2)
  
# This code is contributed by phasing17


C#




// Program to add two polynomials represented
// in linkedlist using recursion
  
using System;
  
class Node {
    public int coeff, power;
    public Node next;
    public Node(int coeff, int power)
    {
        this.coeff = coeff;
        this.power = power;
        this.next = null;
    }
}
  
class Program {
    public static void Main(string[] args)
    {
        Node head = new Node(5, 2);
        insert(head, 4, 1);
        Node head2 = new Node(6, 2);
        insert(head2, 4, 1);
        printList(head);
        Console.WriteLine();
        printList(head2);
        Console.WriteLine("\nAddition:");
        addPolynomials(head, head2);
    }
    static void insert(Node head, int coeff, int power)
    {
        Node new_node = new Node(coeff, power);
        while (head.next != null) {
            head = head.next;
        }
        head.next = new_node;
    }
    static void printList(Node head)
    {
        Console.WriteLine("Linked List");
        while (head != null) {
            Console.Write(" " + head.coeff + "x"
                          + "^" + head.power);
            head = head.next;
        }
    }
    static void addPolynomials(Node head1, Node head2)
    {
        if (head1 == null && head2 == null)
            return;
        else if (head1.power == head2.power) {
            Console.Write(" " + (head1.coeff + head2.coeff)
                          + "x^" + head1.power + " ");
            addPolynomials(head1.next, head2.next);
        }
        else if (head1.power > head2.power) {
            Console.Write(" " + head1.coeff + "x^"
                          + head1.power + " ");
            addPolynomials(head1.next, head2);
        }
        else {
            Console.Write(" " + head2.coeff + "x^"
                          + head2.power + " ");
            addPolynomials(head1, head2.next);
        }
    }
}
  
// This code is contributed by Tapesh(tapeshdua420)


Javascript




<script>
  
// JavaScript Program to add two polynomials
// represented in linkedlist using recursion
  
class Node{
  constructor(coeff, power){
        this.coeff = coeff;
        this.power = power;
        this.next = null;
  }
}
  
function addPolynomials(head1, head2){
  document.write(head1.power, head2.power)
  
  if(head1==null && head2==null)
    return;
  else if(head1.power == head2.power){
    document.write(` ${head1.coeff + head2.coeff}x^${head1.power} `);
    addPolynomials(head1.next, head2.next);
  }
  else if(head1.power > head2.power){
    document.write(` ${head1.coeff}x^${head1.power} `);
    addPolynomials(head1.next, head2);
  }
  else{
    document.write(` ${head2.coeff}x^${head2.power} `);
    addPolynomials(head1, head2.next);
  }
}
  
function insert(head, coeff, power){
  let new_node = new Node(coeff,power);
  while(head.next!=null){
    head = head.next;
  }
  head.next = new_node;
}
  
function printList(head){
  document.write("Linked List","</br>");
  while(head != null){
    document.write(` ${head.coeff}x^${head.power}`);
    head = head.next;
  }
}
  
// driver code
let head = new Node(5,2);
insert(head,4,1);
let head2 = new Node(6,2);
insert(head2,4,1);
printList(head);
document.write("</br>");
printList(head2);
document.write("</br>");
document.write("Addition:");
document.write("</br>");
addPolynomials(head,head2);
  
// This code is contributed by shinjanpatra
  
</script>


Output

Linked List
 5x^2 4x^1
Linked List
 6x^2 4x^1
Addition:
 11x^2  8x^1 

Time Complexity: O(m + n) where m and n are number of nodes in first and second lists respectively.
Auxiliary Space: O(m + n) where m and n are number of nodes in first and second lists respectively due to recursion.

Related Article: Add two polynomial numbers using Arrays 

 



Last Updated : 16 Feb, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads