Polynomial Addition Using Linked List
A polynomial can be stored as a linked list with one node per non-zero term. Two such lists are added in a single pass, like merging two sorted lists, by comparing exponents.
Polynomial Representation Using Linked List
- Node – each term is stored as (coefficient, exponent, next).
- Order – nodes are linked from the highest exponent to the lowest.
- Sparse – terms with coefficient zero get no node at all.
- End – the last node's next pointer is null; an empty list is the zero polynomial.
A polynomial such as 3x⁵ − 4x² + 9 is a sum of terms, each with a coefficient and an exponent. In the linked list representation every non-zero term becomes one node with three fields: the coefficient, the exponent, and a next pointer to the following term. The list is kept in decreasing order of exponent, and the last node's next pointer is null.
In C the node is a structure: struct Node { int coef; int exp; struct Node *next; };. The listings below use the same three fields in Python, C++ and Java. Keeping the order fixed matters: every algorithm on this page relies on it.
- 3x⁵ − 4x² + 9 → (3, 5) → (−4, 2) → (9, 0) → null
- No two nodes in one list share an exponent
- The head pointer identifies the whole polynomial
Why Use a Linked List for Polynomials
A polynomial can also be stored as an array of coefficients indexed by exponent, as the lower half of the diagram shows. That works well for dense polynomials, where most powers are present. But for a sparse polynomial like x¹⁰⁰⁰ + 1, the array needs 1001 slots to hold 2 terms, while the list needs 2 nodes.
A list also grows and shrinks freely: adding a new term means linking in one node, with no resizing or shifting. The price is that you cannot jump straight to the coefficient of x⁵; you must walk the list. For addition and multiplication, which visit every term anyway, that costs nothing.
| Aspect | Coefficient array | Linked list |
|---|---|---|
| Space | degree + 1 slots, zeros included | one node per non-zero term |
| Sparse polynomial x¹⁰⁰⁰ + 1 | 1001 slots | 2 nodes |
| Find the coefficient of xᵏ | O(1): index k | O(terms): walk the list |
| Add a new term | may need to resize | link one node |
| Addition of two polynomials | O(max degree) | O(m + n) terms |
- Each node stores the exponent and a pointer as well as the coefficient, so a list uses about three times the memory per term
- Rule of thumb: once fewer than about a third of the powers are present, the list is smaller
The Merge Algorithm, Step by Step
- Start – set p = head of P, q = head of Q, and an empty result with a tail pointer.
- p.exp > q.exp – append (p.coef, p.exp) to the result and advance p.
- p.exp < q.exp – append (q.coef, q.exp) and advance q.
- p.exp = q.exp – compute sum = p.coef + q.coef; if sum ≠ 0 append (sum, p.exp); advance both.
- Leftovers – when either pointer is null, append every remaining node of the other list.
- Return – the result's head is P + Q.
Adding two polynomials P and Q works exactly like merging two sorted lists. Two pointers, p and q, start at the heads. At each step compare their exponents: the larger exponent cannot match anything still to come in the other list, so its term is copied to the result; equal exponents are like terms, so their coefficients are added.
Two details make the result correct. A sum of zero, such as 3x² + (−3x²), must produce no node. And when one list runs out, the rest of the other list is copied unchanged. Appending at a tail pointer, or after a dummy head node as the listings do, keeps each append O(1).
- Input lists are not modified; the result gets new nodes
- The result stays in decreasing order of exponent automatically
- Subtraction is the same algorithm with Q's coefficients negated
Terms, operations, and practical uses
Core vocabulary
- Term nodeA list node holding a coefficient, an exponent and a next pointer.
- Like termsTerms with the same exponent, whose coefficients are added.
- Sparse polynomialOne where most powers have coefficient zero, like x¹⁰⁰⁰ + 1.
- Tail pointerA pointer to the last node, so appending is O(1).
Rules
- OrderDecreasing exponent, no repeated exponents, no zero coefficients
- AdditionLarger exponent copied; equal exponents summed; zero sums dropped
- Multiplication(a·xⁱ)(b·xʲ) = ab·xⁱ⁺ʲ, then combine like terms
- ComplexityAddition O(m + n); multiplication at least O(m·n)
Related lessons
- Linked ListsNodes, pointers, insertion and traversal.
- Singly Linked ListsThe one-way lists polynomials are stored in.
- Sparse ArraysThe same idea: store only the non-zero entries.
- Two PointersThe merge pattern the addition loop follows.
Code in Python, C++ and Java
class Node:
def __init__(self, coef, exp, next=None):
self.coef = coef
self.exp = exp
self.next = next
def build(terms):
# terms: (coef, exp) pairs in decreasing order of exponent.
head = None
for coef, exp in reversed(terms):
head = Node(coef, exp, head)
return head
def add(p, q):
dummy = tail = Node(0, 0)
while p and q:
if p.exp > q.exp:
coef, exp, p = p.coef, p.exp, p.next
elif p.exp < q.exp:
coef, exp, q = q.coef, q.exp, q.next
else: # like terms: add the coefficients
coef, exp, p, q = p.coef + q.coef, p.exp, p.next, q.next
if coef != 0: # terms that cancel get no node
tail.next = Node(coef, exp)
tail = tail.next
rest = p or q # at most one list has terms left
while rest:
tail.next = Node(rest.coef, rest.exp)
tail, rest = tail.next, rest.next
return dummy.next
def multiply(p, q):
# Multiply every term of p by q, and add each partial product into the result.
result = None
while p:
partial, t = [], q
while t:
partial.append((p.coef * t.coef, p.exp + t.exp))
t = t.next
result = add(result, build(partial))
p = p.next
return result
def evaluate(poly, x):
total = 0
while poly:
total += poly.coef * x**poly.exp
poly = poly.next
return total
def show(poly):
parts = []
while poly:
c, e = poly.coef, poly.exp
coef = "" if abs(c) == 1 and e else str(abs(c))
var = "" if e == 0 else "x" if e == 1 else f"x^{e}"
if parts:
sign = " - " if c < 0 else " + "
else:
sign = "-" if c < 0 else ""
parts.append(sign + coef + var)
poly = poly.next
return "".join(parts) or "0"
P = build([(5, 4), (3, 2), (2, 1), (1, 0)])
Q = build([(6, 3), (-3, 2), (4, 1)])
S = add(P, Q)
print("P =", show(P))
print("Q =", show(Q))
print("P + Q =", show(S))
print(f"check at x = 2: P(2) + Q(2) = {evaluate(P, 2)} + {evaluate(Q, 2)}", end="")
print(f" = {evaluate(S, 2)}")
print("P * Q =", show(multiply(P, Q)))#include <cstdio>
#include <cstdlib>
#include <string>
#include <utility>
#include <vector>
using namespace std;
struct Node {
int coef, exp;
Node* next;
};
// terms: (coef, exp) pairs in decreasing order of exponent.
Node* build(const vector<pair<int, int>>& terms) {
Node* head = nullptr;
for (auto it = terms.rbegin(); it != terms.rend(); ++it) head = new Node{it->first, it->second, head};
return head;
}
Node* add(Node* p, Node* q) {
Node dummy{0, 0, nullptr};
Node* tail = &dummy;
while (p && q) {
int coef, exp;
if (p->exp > q->exp) {
coef = p->coef, exp = p->exp, p = p->next;
} else if (p->exp < q->exp) {
coef = q->coef, exp = q->exp, q = q->next;
} else { // like terms: add the coefficients
coef = p->coef + q->coef, exp = p->exp, p = p->next, q = q->next;
}
if (coef != 0) { // terms that cancel get no node
tail->next = new Node{coef, exp, nullptr};
tail = tail->next;
}
}
for (Node* rest = p ? p : q; rest; rest = rest->next) { // at most one list has terms left
tail->next = new Node{rest->coef, rest->exp, nullptr};
tail = tail->next;
}
return dummy.next;
}
// Multiply every term of p by q, and add each partial product into the result.
Node* multiply(Node* p, Node* q) {
Node* result = nullptr;
for (; p; p = p->next) {
vector<pair<int, int>> partial;
for (Node* t = q; t; t = t->next) partial.push_back({p->coef * t->coef, p->exp + t->exp});
result = add(result, build(partial)); // old lists are not freed, to keep the example short
}
return result;
}
long evaluate(Node* poly, int x) {
long total = 0;
for (; poly; poly = poly->next) {
long power = 1;
for (int i = 0; i < poly->exp; i++) power *= x;
total += poly->coef * power;
}
return total;
}
string show(Node* poly) {
string out;
for (; poly; poly = poly->next) {
int c = poly->coef, e = poly->exp;
string coef = abs(c) == 1 && e ? "" : to_string(abs(c));
string var = e == 0 ? "" : e == 1 ? "x" : "x^" + to_string(e);
string sign = out.empty() ? (c < 0 ? "-" : "") : (c < 0 ? " - " : " + ");
out += sign + coef + var;
}
return out.empty() ? "0" : out;
}
int main() {
Node* P = build({{5, 4}, {3, 2}, {2, 1}, {1, 0}});
Node* Q = build({{6, 3}, {-3, 2}, {4, 1}});
Node* S = add(P, Q);
printf("P = %s\n", show(P).c_str());
printf("Q = %s\n", show(Q).c_str());
printf("P + Q = %s\n", show(S).c_str());
printf("check at x = 2: P(2) + Q(2) = %ld + %ld = %ld\n", evaluate(P, 2), evaluate(Q, 2), evaluate(S, 2));
printf("P * Q = %s\n", show(multiply(P, Q)).c_str());
return 0;
}import java.util.ArrayList;
import java.util.List;
public class Main {
static class Node {
final int coef, exp;
Node next;
Node(int coef, int exp, Node next) {
this.coef = coef;
this.exp = exp;
this.next = next;
}
}
// terms: {coef, exp} pairs in decreasing order of exponent.
static Node build(int[][] terms) {
Node head = null;
for (int i = terms.length - 1; i >= 0; i--) head = new Node(terms[i][0], terms[i][1], head);
return head;
}
static Node add(Node p, Node q) {
Node dummy = new Node(0, 0, null), tail = dummy;
while (p != null && q != null) {
int coef, exp;
if (p.exp > q.exp) {
coef = p.coef;
exp = p.exp;
p = p.next;
} else if (p.exp < q.exp) {
coef = q.coef;
exp = q.exp;
q = q.next;
} else { // like terms: add the coefficients
coef = p.coef + q.coef;
exp = p.exp;
p = p.next;
q = q.next;
}
if (coef != 0) { // terms that cancel get no node
tail.next = new Node(coef, exp, null);
tail = tail.next;
}
}
for (Node rest = p != null ? p : q; rest != null; rest = rest.next) { // at most one list is left
tail.next = new Node(rest.coef, rest.exp, null);
tail = tail.next;
}
return dummy.next;
}
// Multiply every term of p by q, and add each partial product into the result.
static Node multiply(Node p, Node q) {
Node result = null;
for (; p != null; p = p.next) {
List<int[]> partial = new ArrayList<>();
for (Node t = q; t != null; t = t.next) partial.add(new int[] {p.coef * t.coef, p.exp + t.exp});
result = add(result, build(partial.toArray(new int[0][])));
}
return result;
}
static long evaluate(Node poly, int x) {
long total = 0;
for (; poly != null; poly = poly.next) total += poly.coef * (long) Math.pow(x, poly.exp);
return total;
}
static String show(Node poly) {
StringBuilder out = new StringBuilder();
for (; poly != null; poly = poly.next) {
int c = poly.coef, e = poly.exp;
String coef = Math.abs(c) == 1 && e != 0 ? "" : String.valueOf(Math.abs(c));
String var = e == 0 ? "" : e == 1 ? "x" : "x^" + e;
String sign = out.length() == 0 ? (c < 0 ? "-" : "") : (c < 0 ? " - " : " + ");
out.append(sign).append(coef).append(var);
}
return out.length() == 0 ? "0" : out.toString();
}
public static void main(String[] args) {
Node P = build(new int[][] {{5, 4}, {3, 2}, {2, 1}, {1, 0}});
Node Q = build(new int[][] {{6, 3}, {-3, 2}, {4, 1}});
Node S = add(P, Q);
System.out.println("P = " + show(P));
System.out.println("Q = " + show(Q));
System.out.println("P + Q = " + show(S));
System.out.printf("check at x = 2: P(2) + Q(2) = %d + %d = %d%n",
evaluate(P, 2), evaluate(Q, 2), evaluate(S, 2));
System.out.println("P * Q = " + show(multiply(P, Q)));
}
}Step through it
Running on P = 5x⁴ + 3x² + 2x + 1, Q = 6x³ − 3x² + 4x; then (2x + 1)(x + 3)
Time and Space Complexity
Every step of the loop advances p, q, or both, and each pointer can advance at most as many times as its list has nodes. With m terms in P and n terms in Q, addition takes O(m + n) time. The result has at most m + n nodes, fewer when like terms combine or cancel, so it needs O(m + n) extra space.
The tracer's example shows the counting: 4 terms plus 3 terms gave 7 input nodes but only 4 result nodes, because one pair combined into 6x and one pair cancelled.
| Operation | Time | Extra space |
|---|---|---|
| Addition / subtraction | O(m + n) | O(m + n) result nodes |
| Multiplication (add each partial product) | O(m²·n) worst case | O(m·n) |
| Multiplication (collect products, then sort) | O(m·n·log(m·n)) | O(m·n) |
| Evaluation at x | O(t·log e): one fast power per term | O(1) |
- Addition is optimal: every term must be read at least once
- Keeping lists sorted is what avoids an O(m·n) search for like terms
- Unsorted input must be sorted first, in O(m log m + n log n)
Polynomial Multiplication Using Linked List
- For each term of P – multiply it by every term of Q to get a partial product list.
- Add – add the partial product into the result using polynomial addition.
- Repeat – after the last term of P, the result is P × Q, sorted, with like terms combined.
To multiply P by Q, multiply every term of P by every term of Q: coefficients multiply and exponents add, so (a·xⁱ)(b·xʲ) = ab·xⁱ⁺ʲ. That gives m·n products, and products with the same exponent must be combined. The listings do this by building each row of products (one term of P times all of Q, which is already in decreasing order) and adding it into the running result with the addition algorithm above.
Take (2x + 1)(x + 3). The first row is 2x · (x + 3) = 2x² + 6x; the second is 1 · (x + 3) = x + 3. Adding the rows gives 2x² + 7x + 3: the two x terms, 6x and x, combined into one node. The tracer steps through this product at the end. For the larger P and Q the listing prints P × Q = 30x⁷ − 15x⁶ + 38x⁵ + 3x⁴ + 12x³ + 5x² + 4x.
- Multiplying P by itself works the same way; both pointers simply walk the same list
- If the result grows large, collecting all m·n products and sorting them once is faster than repeated additions
Common Mistakes
Most wrong answers come from a handful of cases the main loop does not naturally cover. Test with cancelling terms, disjoint exponents and one empty polynomial: the tracer's example includes a cancelling pair and a leftover term for exactly this reason.
- Keeping zero sums gives output like 5x⁴ + 0x² + 1: append only when the sum is non-zero
- Forgetting the leftover terms after the loop makes the lowest terms of one polynomial disappear
- Unsorted input means like terms are never matched: insert in sorted order, or sort first
- Appending by walking from the head makes addition O((m + n)²): keep a tail pointer or a dummy head
- Reusing input nodes in the result means changing the result changes P or Q: create new nodes
- Print with signs handled: 6x³ − 3x², not 6x³ + −3x²
- Related: Linked Lists and Sparse Arrays