- 2069 Poush · 2+3 marks
Polynomial representation and addition algorithm
Short answer
Polynomial terms are stored as nodes (coef, exp, next) in descending exponent order. Addition: traverse both lists, compare exponents; if p.exp > q.exp, append p's term; if <, append q's term; if equal, add coefficients (if non-zero append). Append remaining terms from the non-empty list. Time O(m+n).
How do you represent polynomial equation using linked list? Write an algorithm to add two polynomial equations.
Representation
Each non-zero term of the polynomial is one node holding the coefficient, the exponent and a pointer to the next term. The terms are stored in decreasing order of exponent.
struct term { int coef; int exp; struct term *next; };
Example: 7x⁴ − 3x² + 5
poly -> [7|4]->[-3|2]->[5|0]->NULL
Algorithm POLYADD(p, q) -> result list r
- Set r = NULL (empty). Let p, q point to the first terms.
- While p ≠ NULL and q ≠ NULL:
- If p->exp > q->exp: append term (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: s = p->coef + q->coef; if s ≠ 0 append (s, p->exp) to r; p = p->next; q = q->next.
- While p ≠ NULL: append p's term to r; p = p->next.
- While q ≠ NULL: append q's term to r; q = q->next.
- Return r.
Example: (3x³ + 2x + 1) + (4x² − 2x + 6)
| p term | q term | Action | r |
|---|---|---|---|
| 3x³ | 4x² | p bigger, copy 3x³ | 3x³ |
| 2x | 4x² | q bigger, copy 4x² | 3x³ + 4x² |
| 2x | −2x | equal, sum 0, drop | 3x³ + 4x² |
| 1 | 6 | equal, 1+6 = 7 | 3x³ + 4x² + 7 |
Time is O(m + n) for m and n terms.
✓ Answer checked by Claude Opus 5.5 (high effort)
Related questions
- Polynomial addition using linked list · Data Structure and Algorithm, chapter 4 · asked 3×
- Algorithm to create a single linked list · Data Structure and Algorithm, chapter 4
- Add objects of two different classes · Object Oriented Programming, chapter 4 · asked 2×
- Algorithm for unsteady pipe flow FD equations · Computational Techniques in Civil Engineering, chapter 6
- Time class: add two objects · Object Oriented Programming, chapter 1
- 8085 ALP: add two tables, sum and carry · Microprocessor, chapter 2