bugfree Icon
interview-course
interview-course
interview-course
interview-course
interview-course
interview-course
interview-course
interview-course

Leetcode Problem 445. Add Two Numbers II

445. Add Two Numbers II

Leetcode Solutions

Stack Approach for Adding Two Numbers as Linked Lists

  1. Initialize two stacks, s1 and s2.
  2. Traverse l1 and push all its elements onto s1.
  3. Traverse l2 and push all its elements onto s2.
  4. Initialize carry to 0 and ans to a new ListNode with value 0.
  5. While s1 or s2 is not empty or carry is not 0: a. Pop elements from s1 and s2 if they are not empty and add them to carry. b. The new digit is carry % 10 and the new carry is carry / 10. c. Create a new node with the new digit and set it as the next of ans. d. Update ans to this new node.
  6. Reverse the resulting linked list to get the correct order.
  7. Return the reversed list, which is the sum of the two numbers.
UML Thumbnail

Reverse Linked Lists and Add Approach

Ask Question

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

Suggested Answer

Answer
Full Screen
Copy Answer Code
Loading...