- Asked 3/14
- 2074 Bhadra · 5 marks
- 2072 Magh · 4 marks
- 2071 Magh · 5 marks
Polynomial addition using linked list
Short answer
Two polynomials stored as linked lists in decreasing exponent order are added by merging-like traversal: compare exponents, sum coefficients if equal, skip zero sums. Resulting polynomial has no zero terms. Time is O(m+n). Example: 5x³+4x²+2 and 3x³-4x²+7x+1 yield 8x³+7x+3.
Explain how the addition of two polynomials is done using linked list.
A polynomial is stored as a linked list where each node holds one non-zero term: its coefficient, its exponent and a link to the next term. Terms are kept in decreasing order of exponent, so two polynomials can be added by walking through both lists together (like merging).
struct term {
int coef; /* coefficient */
int exp; /* exponent */
struct term *next;
};
Example
P = 5x³ + 4x² + 2 and Q = 3x³ − 4x² + 7x + 1
P: [5|3]->[4|2]->[2|0]->NULL
Q: [3|3]->[-4|2]->[7|1]->[1|0]->NULL
Algorithm (p points to P, q to Q, R is the result list)
- Set
pandqto the first nodes; R is empty. - While
p != NULLandq != NULL:- if
p->exp > q->exp: append (p->coef, p->exp) to R;p = p->next. - else if
p->exp < q->exp: append (q->coef, q->exp) to R;q = q->next. - else (equal exponents):
sum = p->coef + q->coef; if sum ≠ 0 append (sum, p->exp) to R; move bothpandq.
- if
- Copy the remaining nodes of whichever list is not finished to R.
- Return R.
Trace
| Step | p term | q term | Action | R so far |
|---|---|---|---|---|
| 1 | 5x³ | 3x³ | equal, 5+3 = 8 | 8x³ |
| 2 | 4x² | −4x² | equal, sum 0, skip | 8x³ |
| 3 | 2x⁰ | 7x¹ | q larger, copy 7x | 8x³ + 7x |
| 4 | 2x⁰ | 1x⁰ | equal, 2+1 = 3 | 8x³ + 7x + 3 |
Result: R = 8x³ + 7x + 3 (checked by running the C code below).
struct term *add(struct term *p, struct term *q) {
struct term head, *t = &head; /* dummy head simplifies appending */
head.next = NULL;
while (p && q) {
if (p->exp > q->exp) { t->next = mk(p->coef, p->exp); p = p->next; t = t->next; }
else if (p->exp < q->exp) { t->next = mk(q->coef, q->exp); q = q->next; t = t->next; }
else {
int s = p->coef + q->coef;
if (s != 0) { t->next = mk(s, p->exp); t = t->next; }
p = p->next; q = q->next;
}
}
for (; p; p = p->next) { t->next = mk(p->coef, p->exp); t = t->next; }
for (; q; q = q->next) { t->next = mk(q->coef, q->exp); t = t->next; }
return head.next;
}
mk(c, e) allocates a node with coefficient c, exponent e and next = NULL. Time is O(m + n) for lists of m and n terms.
✓ Answer checked by Claude Opus 5.5 (high effort)
Related questions
- Polynomial representation and addition algorithm · Data Structure and Algorithm, chapter 4
- Express x³−5x²+x+2 in Legendre polynomials · Mathematics, chapter 4 · asked 3×