445. 两数相加 II

image.png
image.png

题解

辅助栈

image.png

  1. class Solution {
  2. public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
  3. Stack<ListNode> stack1 = new Stack<>();
  4. Stack<ListNode> stack2 = new Stack<>();
  5. while (l1 != null) {
  6. stack1.push(l1);
  7. l1 = l1.next;
  8. }
  9. while (l2 != null) {
  10. stack2.push(l2);
  11. l2 = l2.next;
  12. }
  13. // 记录是否进位
  14. int tip = 0;
  15. ListNode ans = null;
  16. while (!stack1.isEmpty() || !stack2.isEmpty() || tip != 0) {
  17. int l1Val = stack1.isEmpty() ? 0 : stack1.pop().val;
  18. int l2Val = stack2.isEmpty() ? 0 : stack2.pop().val;
  19. int sum = l1Val + l2Val + tip;
  20. tip = sum / 10;
  21. ListNode curNode = new ListNode(sum % 10);
  22. curNode.next = ans;
  23. ans = curNode;
  24. }
  25. return ans;
  26. }
  27. }