Leetcode Problem 1634. Add Two Polynomials Represented as Linked Lists

1634. Add Two Polynomials Represented as Linked Lists

Leetcode Solutions

Merge Two Polynomial Linked Lists

  1. Create a dummy head for the result linked list.
  2. Initialize a pointer current to track the end of the result list.
  3. While both poly1 and poly2 are not null: a. If poly1.power is greater than poly2.power, attach poly1 to current and move poly1 forward. b. If poly2.power is greater than poly1.power, attach poly2 to current and move poly2 forward. c. If both powers are equal, add the coefficients and create a new node with the sum if it's non-zero, then move both poly1 and poly2 forward.
  4. If one of the lists is not finished, attach the remaining part to current.
  5. Return the next of the dummy head as the start of the result list.
UML Thumbnail

Iterative Addition with Node Reuse

Ask Question

Programming Language
image/screenshot of info(optional)
Full Screen
Loading...

Suggested Answer

Answer
Full Screen
Copy Answer Code
Loading...