Problem Description
Given two polynomial linked lists poly1 and poly2, where each node represents a term of the polynomial (with a coefficient and a power), add these two polynomials and return the resulting polynomial as a linked list in standard form (strictly descending order by power and excluding any term with a coefficient of 0).
Key Insights
- The linked lists are sorted in descending order by power.
- Use two pointers to traverse both lists simultaneously.
- When both nodes have the same power, add the coefficients.
- If one list's current node has a higher power than the other's, take that node directly.
- Omit any term that becomes 0 after adding coefficients.
- Edge case: if the sum is 0, return an empty list.
Space and Time Complexity
Time Complexity: O(n + m), where n and m are the lengths of poly1 and poly2 respectively. Space Complexity: O(n + m) in the worst-case scenario for the resulting linked list.
Solution
Use two pointers to traverse poly1 and poly2. Compare the power of the nodes:
- If poly1.power > poly2.power, append poly1's node to the result and move poly1 forward.
- If poly1.power < poly2.power, append poly2's node and move poly2 forward.
- If the powers are equal, sum the coefficients and if the result is non-zero, append a new node with this sum. Continue until both lists are exhausted, appending any remaining nodes from the non-empty list. The dummy head trick simplifies managing the result list.