Polynomial addition using linked list
Represent a Polynomial using Linked List
✅ A polynomial is a mathematical expression like:
✅ To represent this using a linked list, we create a node for each term.
✅ Each node contains:
-
Coefficient (example: 5, 4, 2, 7)
-
Exponent (example: 3, 2, 1, 0)
-
Pointer to the next node
✅ Linked list nodes are connected from highest exponent to lowest exponent.
Structure of a Node
In C language, the structure will look like:
Example
For polynomial:
4x^3+9x^2+6x+7Linked list will look like:
Where [coefficient, exponent] is stored inside each node.
Why Linked List for Polynomials?
-
Easy to add, subtract, or multiply polynomials.
-
Can easily insert and delete terms.
-
Memory efficient — no wasted space.
Algorithm to Create a Polynomial Linked List
Algorithm CreatePolynomial():
-
Start with
head = NULL -
Repeat until the user finishes entering terms:
-
Read coefficient and exponent
-
Create a new node with the given coefficient and exponent
-
If head == NULL:
-
Set head = new node
-
-
Else:
-
Attach new node at the end
-
-
-
Return head
Adding Two Polynomials
-
Each polynomial is stored as a linked list with (coefficient, exponent) pairs.
-
Compare exponents:
-
If exponents are equal, add coefficients and create a new term.
-
If exponent of first polynomial is greater, copy that term.
-
If exponent of second polynomial is greater, copy that term.
-
-
Move forward in the respective list after handling each term.
Algorithm: AddPolynomials(P1, P2)
Input:
Two polynomial linked lists P1 and P2 (sorted by decreasing exponents).
Output:
A new polynomial linked list representing the sum.
Steps:
-
Start
-
Create a new empty list
Result -
Set pointers
ptr1to head ofP1, andptr2to head ofP2 -
While both
ptr1andptr2are not NULL:-
If
ptr1->exp > ptr2->exp:-
Create new node with
ptr1->coeffandptr1->exp -
Move
ptr1to next node
-
-
Else if
ptr2->exp > ptr1->exp:-
Create new node with
ptr2->coeffandptr2->exp -
Move
ptr2to next node
-
-
Else (exponents are equal):
-
Sum =
ptr1->coeff + ptr2->coeff -
If sum ≠ 0:
-
Create new node with
sumandptr1->exp
-
-
Move both
ptr1andptr2to next nodes
-
-
-
While
ptr1is not NULL:-
Copy remaining terms from
ptr1to Result
-
-
While
ptr2is not NULL:-
Copy remaining terms from
ptr2to Result
-
-
End
Example
Suppose:
P1 = 5x⁴ + 3x² + 1
P2 = 6x³ + 2x² + 8
Addition step-by-step:
| Compare | Action |
|---|---|
| 5x⁴ vs 6x³ | 5x⁴ copied |
| 6x³ vs 3x² | 6x³ copied |
| 3x² vs 2x² | 3+2 = 5 ⇒ 5x² |
| 1 vs 8 | 1+8 = 9 ⇒ 9 |
Result = 5x⁴ + 6x³ + 5x² + 9
C program - Polynomial addition using Linked List
Comments
Post a Comment