题目

You are given two non-empty linked lists representing two non-negative integers. The most significant digit comes first and each of their nodes contain a single digit. Add the two numbers and return it as a linked list.

You may assume the two numbers do not contain any leading zero, except the number 0 itself.

Follow up:
What if you cannot modify the input lists? In other words, reversing the lists is not allowed.

Example:

  1. Input: (7 -> 2 -> 4 -> 3) + (5 -> 6 -> 4)
  2. Output: 7 -> 8 -> 0 -> 7

题意

给定两个用链表表示的整数,计算它们的和并同样用链表表示。

思路

不逆序链表的话,可以用栈处理。


代码实现

Java

  1. class Solution {
  2. public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
  3. ListNode head = null;
  4. Deque<Integer> A = new ArrayDeque<>();
  5. Deque<Integer> B = new ArrayDeque<>();
  6. int carry = 0;
  7. while (l1 != null) {
  8. A.push(l1.val);
  9. l1 = l1.next;
  10. }
  11. while (l2 != null) {
  12. B.push(l2.val);
  13. l2 = l2.next;
  14. }
  15. while (!A.isEmpty() || !B.isEmpty()) {
  16. int a = A.isEmpty() ? 0 : A.pop();
  17. int b = B.isEmpty() ? 0 : B.pop();
  18. int sum = a + b + carry;
  19. carry = sum / 10;
  20. sum = sum % 10;
  21. head = new ListNode(sum, head);
  22. }
  23. if (carry > 0) {
  24. head = new ListNode(carry, head);
  25. }
  26. return head;
  27. }
  28. }