Polynomials Addition
This is a classic problem, usually solved with either two-pointers (merge-sort style), or a simple recursion. In the case below, I have opted for a recursive solution. Here is the problem: https://leetcode.com/problems/add-two-polynomials-represented-as-linked-lists/
The recursion will have one base case followed by four induction steps. Base case is straightforward. The four induction steps are: head of poly1 greater than head of poly2, head of poly2 greater than head of poly1, both being the same but the addition leading to a zero coefficient, or finally both being the same and the sum not leading to a zero coefficient. Works well, code is below, cheers! ACC
public PolyNode AddPoly(PolyNode poly1, PolyNode poly2)
{
if (poly1 == null) return poly2;
if (poly2 == null) return poly1;
if (poly1.power > poly2.power)
return new PolyNode(poly1.coefficient, poly1.power, AddPoly(poly1.next, poly2));
else if (poly1.power < poly2.power)
return new PolyNode(poly2.coefficient, poly2.power, AddPoly(poly1, poly2.next));
else if (poly1.coefficient + poly2.coefficient == 0)
return AddPoly(poly1.next, poly2.next);
else
return new PolyNode(poly1.coefficient + poly2.coefficient, poly1.power, AddPoly(poly1.next, poly2.next));
}

Comments
Post a Comment