Adding two polynomials using Linked List (original) (raw)

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

Table of Content

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

C++ `

// C++ program to add two polynomials #include <bits/stdc++.h> using namespace std;

class Node { public: int coeff; int pow; Node* next; Node(int c, int p) { coeff = c; pow = p; next = nullptr; } };

Node* addPolynomial(Node* head1, Node* head2) {

// if any list is empty, then return
// the other list.
if (head1 == nullptr) return head2;
if (head2 == nullptr) return head1;

// If head1.pow is greater, then recursively find
// its next node, and return head1.
if (head1->pow > head2->pow) {
  Node* nextPtr = addPolynomial(head1->next, head2);
  head1->next = nextPtr;
  return head1;
}

// If head2.pow is greater, then recusrively find its 
// next node, and return head2.
else if (head1->pow < head2->pow) {
  Node* nextPtr = addPolynomial(head1, head2->next);
  head2->next = nextPtr;
  return head2;
}

// else store the sum of head1.coeff and head2.coeff in
// head1->coeff, then find its next node and return head1.
Node* nextPtr = addPolynomial(head1->next, head2->next);
head1->coeff += head2->coeff;
head1->next = nextPtr;
return head1;

}

void printList(Node* head) { Node* curr = head;

while (curr != nullptr) {
    cout << curr->coeff << "," << curr->pow <<" ";
    curr = curr->next;
}

cout<<endl;

}

int main() {

// 1st polynomial: 5x^2+4x^1+2x^0
Node* head1 = new Node(5,2); 
head1->next = new Node(4,1);
head1->next->next = new Node(2,0);

// 2nd polynomial: -5x^1-5x^0
Node* head2 = new Node(-5,1); 
head2->next = new Node(-5,0);


Node* head = addPolynomial(head1, head2);

printList(head);

}

C

// C program to add two polynomials #include <stdio.h> #include <stdlib.h>

struct Node { int coeff; int pow; struct Node* next; };

struct Node* createNode(int c, int p);

struct Node* addPolynomial(struct Node* head1, struct Node* head2) {

// if any list is empty, then return
// the other list.
if (head1 == NULL) return head2;
if (head2 == NULL) return head1;

// If head1.pow is greater, then recursively find
// its next node, and return head1.
if (head1->pow > head2->pow) {
    struct Node* nextPtr = 
      addPolynomial(head1->next, head2);
    head1->next = nextPtr;
    return head1;
}

// If head2.pow is greater, then recursively find its 
// next node, and return head2.
else if (head1->pow < head2->pow) {
    struct Node* nextPtr = 
      addPolynomial(head1, head2->next);
    head2->next = nextPtr;
    return head2;
}

// else store the sum of head1.coeff and head2.coeff in
// head1->coeff, then find its next node and return head1.
struct Node* nextPtr = 
      addPolynomial(head1->next, head2->next);
head1->coeff += head2->coeff;
head1->next = nextPtr;
return head1;

}

void printList(struct Node* head) { struct Node* curr = head;

while (curr != NULL) {
    printf("%d,%d ", curr->coeff, curr->pow);
    curr = curr->next;

}

printf("\n");

}

struct Node* createNode(int c, int p) { struct Node* newNode = (struct Node*)malloc(sizeof(struct Node)); newNode->coeff = c; newNode->pow = p; newNode->next = NULL; return newNode; }

int main() {

// 1st polynomial: 5x^2+4x^1+2x^0
struct Node* head1 = createNode(5, 2);
head1->next = createNode(4, 1);
head1->next->next = createNode(2, 0);

// 2nd polynomial: -5x^1-5x^0
struct Node* head2 = createNode(-5, 1);
head2->next = createNode(-5, 0);

struct Node* head = addPolynomial(head1, head2);

printList(head);

return 0;

}

Java

// Java program to add two polynomials

class Node { int coeff; int pow; Node next; Node(int c, int p) { coeff = c; pow = p; next = null; } }

class Main {

static Node addPolynomial(Node head1, Node head2) {
    
    // if any list is empty, then return
    // the other list.
    if (head1 == null) return head2;
    if (head2 == null) return head1;
    
    // If head1.pow is greater, then recursively find
    // its next node, and return head1.
    if (head1.pow > head2.pow) {
        Node nextPtr = addPolynomial(head1.next, head2);
        head1.next = nextPtr;
        return head1;
    }

    // If head2.pow is greater, then recursively find its 
    // next node, and return head2.
    else if (head1.pow < head2.pow) {
        Node nextPtr = addPolynomial(head1, head2.next);
        head2.next = nextPtr;
        return head2;
    }

    // else store the sum of head1.coeff and head2.coeff in
    // head1.coeff, then find its next node and return head1.
    Node nextPtr = addPolynomial(head1.next, head2.next);
    head1.coeff += head2.coeff;
    head1.next = nextPtr;
    return head1;
}

static void printList(Node head) {
    Node curr = head;

    while (curr != null) {
        System.out.print(curr.coeff + "," + curr.pow + " ");
        curr = curr.next;
    }

    System.out.println();
}

public static void main(String[] args) {
    
    // 1st polynomial: 5x^2+4x^1+2x^0
    Node head1 = new Node(5, 2);
    head1.next = new Node(4, 1);
    head1.next.next = new Node(2, 0);

    // 2nd polynomial: -5x^1-5x^0
    Node head2 = new Node(-5, 1);
    head2.next = new Node(-5, 0);

    Node head = addPolynomial(head1, head2);

    printList(head);
}

}

Python

Python program to add two polynomials

class Node: def init(self, c, p): self.coeff = c self.pow = p self.next = None

def add_polynomial(head1, head2):

# if any list is empty, then return
# the other list.
if head1 is None:
    return head2
if head2 is None:
    return head1

# If head1.pow is greater, then recursively find
# its next node, and return head1.
if head1.pow > head2.pow:
    next_ptr = add_polynomial(head1.next, head2)
    head1.next = next_ptr
    return head1

# If head2.pow is greater, then recursively find its 
# next node, and return head2.
elif head1.pow < head2.pow:
    next_ptr = add_polynomial(head1, head2.next)
    head2.next = next_ptr
    return head2

# else store the sum of head1.coeff and head2.coeff in
# head1.coeff, then find its next node and return head1.
next_ptr = add_polynomial(head1.next, head2.next)
head1.coeff += head2.coeff
head1.next = next_ptr
return head1

def print_list(head): curr = head

while curr is not None:
    print(f"{curr.coeff},{curr.pow}", end=" ")
    curr = curr.next

print()

if name == "main":

# 1st polynomial: 5x^2+4x^1+2x^0
head1 = Node(5, 2)
head1.next = Node(4, 1)
head1.next.next = Node(2, 0)

# 2nd polynomial: -5x^1-5x^0
head2 = Node(-5, 1)
head2.next = Node(-5, 0)

head = add_polynomial(head1, head2)

print_list(head)

C#

// C# program to add two polynomials

class Node { public int coeff; public int pow; public Node next; public Node(int c, int p) { coeff = c; pow = p; next = null; } }

class GfG {

static Node AddPolynomial(Node head1, Node head2) {
  
    // if any list is empty, then return
    // the other list.
    if (head1 == null) return head2;
    if (head2 == null) return head1;
    
    Node nextPtr;
    
    // If head1.pow is greater, then recursively find
    // its next node, and return head1.
    if (head1.pow > head2.pow) {
        nextPtr = AddPolynomial(head1.next, head2);
        head1.next = nextPtr;
        return head1;
    }

    // If head2.pow is greater, then recursively find its 
    // next node, and return head2.
    else if (head1.pow < head2.pow) {
        nextPtr = AddPolynomial(head1, head2.next);
        head2.next = nextPtr;
        return head2;
    }

    // else store the sum of head1.coeff and head2.coeff in
    // head1.coeff, then find its next node and return head1.
    nextPtr = AddPolynomial(head1.next, head2.next);
    head1.coeff += head2.coeff;
    head1.next = nextPtr;
    return head1;
}

static void PrintList(Node head) {
    Node curr = head;

    while (curr != null) {
        System.Console.Write(curr.coeff + "," + curr.pow + " ");
        curr = curr.next;
    }

    System.Console.WriteLine();
}

static void Main(string[] args) {
    
    // 1st polynomial: 5x^2+4x^1+2x^0
    Node head1 = new Node(5, 2);
    head1.next = new Node(4, 1);
    head1.next.next = new Node(2, 0);

    // 2nd polynomial: -5x^1-5x^0
    Node head2 = new Node(-5, 1);
    head2.next = new Node(-5, 0);

    Node head = AddPolynomial(head1, head2);

    PrintList(head);
}

}

JavaScript

// JavaScript program to add two polynomials

class Node { constructor(c, p) { this.coeff = c; this.pow = p; this.next = null; } }

function addPolynomial(head1, head2) {

// if any list is empty, then return
// the other list.
if (head1 === null) return head2;
if (head2 === null) return head1;

// If head1.pow is greater, then recursively find
// its next node, and return head1.
if (head1.pow > head2.pow) {
    let nextPtr = addPolynomial(head1.next, head2);
    head1.next = nextPtr;
    return head1;
}

// If head2.pow is greater, then recursively find its 
// next node, and return head2.
else if (head1.pow < head2.pow) {
    let nextPtr = addPolynomial(head1, head2.next);
    head2.next = nextPtr;
    return head2;
}

// else store the sum of head1.coeff and head2.coeff in
// head1.coeff, then find its next node and return head1.
let nextPtr = addPolynomial(head1.next, head2.next);
head1.coeff += head2.coeff;
head1.next = nextPtr;
return head1;

}

function printList(head) { let curr = head;

while (curr !== null) {
    console.log(curr.coeff+","+curr.pow + " ");
    curr = curr.next;
}

console.log();

}

// 1st polynomial: 5x^2+4x^1+2x^0 let head1 = new Node(5, 2); head1.next = new Node(4, 1); head1.next.next = new Node(2, 0);

// 2nd polynomial: -5x^1-5x^0 let head2 = new Node(-5, 1); head2.next = new Node(-5, 0);

let head = addPolynomial(head1, head2);

printList(head);

`

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

C++ `

// C++ program to add two polynomials #include <bits/stdc++.h> using namespace std;

class Node { public: int coeff; int pow; Node* next; Node(int c, int p) { coeff = c; pow = p; next = nullptr; } };

Node* addPolynomial(Node* head1, Node* head2) { Node* dummy = new Node(0, 0);

// Node to append other nodes to the end 
// of list
Node* prev = dummy;

Node* curr1 = head1, *curr2 = head2;

while (curr1 != nullptr && curr2 != nullptr) {
    
    // if curr2.pow > curr1.pow, then 
    // append curr2 to list
    if (curr1->pow < curr2->pow) {
        prev->next = curr2;
        prev = curr2;
        curr2 = curr2->next;
    }
    
    // if curr1.pow > curr2.pow, then 
    // append curr2 to list
    else if (curr1->pow > curr2->pow) {
        prev->next = curr1;
        prev = curr1;
        curr1 = curr1->next;
    }
    
    // else, add the sum of curr1->coeff and 
    // curr2->coeff to curr1->coeff, and append
    // curr1 to the list
    else {
        curr1->coeff = curr1->coeff + curr2->coeff;
        prev->next = curr1;
        prev = curr1;
        curr1 = curr1->next;
        curr2 = curr2->next;
    }
}

// if curr1 if not null, then append the rest
// to the list
if (curr1 != nullptr) {
    prev->next = curr1;
}

// if curr2 if not null, then append the rest
// to the list
if (curr2 != NULL) {
    prev->next = curr2;
}

return dummy->next;

}

void printList(Node* head) { Node* curr = head;

while (curr != nullptr) {
    cout << curr->coeff << "," << curr->pow << " ";
    curr = curr->next;
    
}

cout<<endl;

}

int main() {

// 1st polynomial: 5x^2+4x^1+2x^0
Node* head1 = new Node(5,2); 
head1->next = new Node(4,1);
head1->next->next = new Node(2,0);

// 2nd polynomial: -5x^1-5x^0
Node* head2 = new Node(-5,1); 
head2->next = new Node(-5,0);

Node* head = addPolynomial(head1, head2);

printList(head);

}

C

// C program to add two polynomials #include <stdio.h> #include <stdlib.h>

struct Node { int coeff; int pow; struct Node* next; };

struct Node* createNode(int c, int p);

struct Node* addPolynomial(struct Node* head1, struct Node* head2) { struct Node* dummy = createNode(0, 0);

// Node to append other nodes to the end 
// of list
struct Node* prev = dummy;
struct Node *curr1 = head1, *curr2 = head2;

while (curr1 != NULL && curr2 != NULL) {

    // if curr2.pow > curr1.pow, then 
    // append curr2 to list
    if (curr1->pow < curr2->pow) {
        prev->next = curr2;
        prev = curr2;
        curr2 = curr2->next;
    }

    // if curr1.pow > curr2.pow, then 
    // append curr2 to list
    else if (curr1->pow > curr2->pow) {
        prev->next = curr1;
        prev = curr1;
        curr1 = curr1->next;
    }

    // else, add the sum of curr1->coeff and 
    // curr2->coeff to curr1->coeff, and append
    // curr1 to the list
    else {
        curr1->coeff = curr1->coeff + curr2->coeff;
        prev->next = curr1;
        prev = curr1;
        curr1 = curr1->next;
        curr2 = curr2->next;
    }
}

// if curr1 is not null, then append the rest
// to the list
if (curr1 != NULL) {
    prev->next = curr1;
}

// if curr2 is not null, then append the rest
// to the list
if (curr2 != NULL) {
    prev->next = curr2;
}

return dummy->next;

}

void printList(struct Node* head) { struct Node* curr = head;

while (curr != NULL) {
    printf("%d,%d ", curr->coeff, curr->pow);
    curr = curr->next;

}

printf("\n");

}

struct Node* createNode(int c, int p) { struct Node* newNode = (struct Node*)malloc(sizeof(struct Node)); newNode->coeff = c; newNode->pow = p; newNode->next = NULL; return newNode; }

int main() {

// 1st polynomial: 5x^2+4x^1+2x^0
struct Node* head1 = createNode(5, 2);
head1->next = createNode(4, 1);
head1->next->next = createNode(2, 0);

// 2nd polynomial: -5x^1-5x^0
struct Node* head2 = createNode(-5, 1);
head2->next = createNode(-5, 0);

struct Node* head = addPolynomial(head1, head2);

printList(head);

return 0;

}

Java

// Java program to add two polynomials

class Node { int coeff; int pow; Node next; Node(int c, int p) { coeff = c; pow = p; next = null; } }

class GfG {

static Node addPolynomial(Node head1, Node head2) {
    Node dummy = new Node(0, 0);

    // Node to append other nodes to the end 
    // of list
    Node prev = dummy;
    Node curr1 = head1, curr2 = head2;

    while (curr1 != null && curr2 != null) {

        // if curr2.pow > curr1.pow, then 
        // append curr2 to list
        if (curr1.pow < curr2.pow) {
            prev.next = curr2;
            prev = curr2;
            curr2 = curr2.next;
        }

        // if curr1.pow > curr2.pow, then 
        // append curr2 to list
        else if (curr1.pow > curr2.pow) {
            prev.next = curr1;
            prev = curr1;
            curr1 = curr1.next;
        }

        // else, add the sum of curr1.coeff and 
        // curr2.coeff to curr1.coeff, and append
        // curr1 to the list
        else {
            curr1.coeff = curr1.coeff + curr2.coeff;
            prev.next = curr1;
            prev = curr1;
            curr1 = curr1.next;
            curr2 = curr2.next;
        }
    }

    // if curr1 if not null, then append the rest
    // to the list
    if (curr1 != null) {
        prev.next = curr1;
    }

    // if curr2 if not null, then append the rest
    // to the list
    if (curr2 != null) {
        prev.next = curr2;
    }

    return dummy.next;
}

static void printList(Node head) {
    Node curr = head;

    while (curr != null) {
        System.out.print(curr.coeff + "," + curr.pow + " ");
        curr = curr.next;
    }

    System.out.println();
}

public static void main(String[] args) {
    
    // 1st polynomial: 5x^2+4x^1+2x^0
    Node head1 = new Node(5, 2);
    head1.next = new Node(4, 1);
    head1.next.next = new Node(2, 0);

    // 2nd polynomial: -5x^1-5x^0
    Node head2 = new Node(-5, 1);
    head2.next = new Node(-5, 0);

    Node head = addPolynomial(head1, head2);

    printList(head);
}

}

Python

Python program to add two polynomials

class Node: def init(self, c, p): self.coeff = c self.pow = p self.next = None

def add_polynomial(head1, head2): dummy = Node(0, 0)

# Node to append other nodes to the end 
# of list
prev = dummy
curr1, curr2 = head1, head2

while curr1 is not None and curr2 is not None:

    # if curr2.pow > curr1.pow, then 
    # append curr2 to list
    if curr1.pow < curr2.pow:
        prev.next = curr2
        prev = curr2
        curr2 = curr2.next

    # if curr1.pow > curr2.pow, then 
    # append curr1 to list
    elif curr1.pow > curr2.pow:
        prev.next = curr1
        prev = curr1
        curr1 = curr1.next

    # else, add the sum of curr1.coeff and 
    # curr2.coeff to curr1.coeff, and append
    # curr1 to the list
    else:
        curr1.coeff = curr1.coeff + curr2.coeff
        prev.next = curr1
        prev = curr1
        curr1 = curr1.next
        curr2 = curr2.next

# if curr1 if not None, then append the rest
# to the list
if curr1 is not None:
    prev.next = curr1

# if curr2 if not None, then append the rest
# to the list
if curr2 is not None:
    prev.next = curr2

return dummy.next

def print_list(head): curr = head

while curr is not None:
    print(f"{curr.coeff},{curr.pow}", end=" ")
    curr = curr.next

print()

if name == "main":

# 1st polynomial: 5x^2+4x^1+2x^0
head1 = Node(5, 2)
head1.next = Node(4, 1)
head1.next.next = Node(2, 0)

# 2nd polynomial: -5x^1-5x^0
head2 = Node(-5, 1)
head2.next = Node(-5, 0)

head = add_polynomial(head1, head2)

print_list(head)

C#

// C# program to add two polynomials

class Node { public int coeff; public int pow; public Node next; public Node(int c, int p) { coeff = c; pow = p; next = null; } }

class GfG {

static Node AddPolynomial(Node head1, Node head2) {
    Node dummy = new Node(0, 0);

    // Node to append other nodes to the end 
    // of list
    Node prev = dummy;
    Node curr1 = head1, curr2 = head2;

    while (curr1 != null && curr2 != null) {

        // if curr2.pow > curr1.pow, then 
        // append curr2 to list
        if (curr1.pow < curr2.pow) {
            prev.next = curr2;
            prev = curr2;
            curr2 = curr2.next;
        }

        // if curr1.pow > curr2.pow, then 
        // append curr1 to list
        else if (curr1.pow > curr2.pow) {
            prev.next = curr1;
            prev = curr1;
            curr1 = curr1.next;
        }

        // else, add the sum of curr1.coeff and 
        // curr2.coeff to curr1.coeff, and append
        // curr1 to the list
        else {
            curr1.coeff = curr1.coeff + curr2.coeff;
            prev.next = curr1;
            prev = curr1;
            curr1 = curr1.next;
            curr2 = curr2.next;
        }
    }

    // if curr1 if not null, then append the rest
    // to the list
    if (curr1 != null) {
        prev.next = curr1;
    }

    // if curr2 if not null, then append the rest
    // to the list
    if (curr2 != null) {
        prev.next = curr2;
    }

    return dummy.next;
}

static void PrintList(Node head) {
    Node curr = head;

    while (curr != null) {
        System.Console.Write(curr.coeff + "," + curr.pow + " ");
        curr = curr.next;
    }

    System.Console.WriteLine();
}

static void Main(string[] args) {
    
    // 1st polynomial: 5x^2+4x^1+2x^0
    Node head1 = new Node(5, 2);
    head1.next = new Node(4, 1);
    head1.next.next = new Node(2, 0);

    // 2nd polynomial: -5x^1-5x^0
    Node head2 = new Node(-5, 1);
    head2.next = new Node(-5, 0);

    Node head = AddPolynomial(head1, head2);

    PrintList(head);
}

}

JavaScript

// JavaScript program to add two polynomials

class Node { constructor(c, p) { this.coeff = c; this.pow = p; this.next = null; } }

function addPolynomial(head1, head2) { let dummy = new Node(0, 0);

// Node to append other nodes to the end 
// of list
let prev = dummy;
let curr1 = head1, curr2 = head2;

while (curr1 !== null && curr2 !== null) {

    // if curr2.pow > curr1.pow, then 
    // append curr2 to list
    if (curr1.pow < curr2.pow) {
        prev.next = curr2;
        prev = curr2;
        curr2 = curr2.next;
    }

    // if curr1.pow > curr2.pow, then 
    // append curr1 to list
    else if (curr1.pow > curr2.pow) {
        prev.next = curr1;
        prev = curr1;
        curr1 = curr1.next;
    }

    // else, add the sum of curr1.coeff and 
    // curr2.coeff to curr1.coeff, and append
    // curr1 to the list
    else {
        curr1.coeff = curr1.coeff + curr2.coeff;
        prev.next = curr1;
        prev = curr1;
        curr1 = curr1.next;
        curr2 = curr2.next;
    }
}

// if curr1 if not null, then append the rest
// to the list
if (curr1 !== null) {
    prev.next = curr1;
}

// if curr2 if not null, then append the rest
// to the list
if (curr2 !== null) {
    prev.next = curr2;
}

return dummy.next;

}

function printList(head) { let curr = head;

while (curr !== null) {
    console.log(curr.coeff+","+curr.pow + " ");
    curr = curr.next;
}

console.log();

}

// 1st polynomial: 5x^2+4x^1+2x^0 let head1 = new Node(5, 2); head1.next = new Node(4, 1); head1.next.next = new Node(2, 0);

// 2nd polynomial: -5x^1-5x^0 let head2 = new Node(-5, 1); head2.next = new Node(-5, 0);

let head = addPolynomial(head1, head2);

printList(head);

`

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