445. Add Two Numbers II

Medium
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:

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

这道题看的答案,一旦理解可谓相当简单,顿时变Easy. 这里要用到三个栈, s1, s2来压链表节点,res来压求和链表。 注意一下每次运算得到的进位carry, 这个进位是下一次循环更低位求和运算时才会用到的。 而digit则是每次运算后该位上的数字,也就是我们要压进res里的节点val.

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution {
    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        if (l1 == null && l2 == null){
            return null;
        }
        if (l1 == null || l2 == null){
            return l1 == null ? l2 : l1;
        }
        Stack<ListNode> s1 = new Stack<>();
        Stack<ListNode> s2 = new Stack<>();
        Stack<ListNode> res = new Stack<>();
        while (l1 != null){
            s1.push(l1);
            l1 = l1.next;
        }
        while (l2 != null){
            s2.push(l2);
            l2 = l2.next;
        }
        int carry = 0;
        while (!s1.isEmpty() || !s2.isEmpty()){
            int sum = 0;
            if (!s1.isEmpty() && !s2.isEmpty()){
                sum += s1.pop().val + s2.pop().val;
            } else if (!s1.isEmpty()){
                sum += s1.pop().val;
            } else if (!s2.isEmpty()){
                sum += s2.pop().val;
            }
            //here, carry is from last loop.
            int digit = (sum + carry) % 10;
            carry = (sum + carry) / 10;
            res.push(new ListNode(digit));
        }
        if (carry == 1){
            res.push(new ListNode(carry));
        }
        ListNode dummy = new ListNode(-1);
        ListNode node = dummy;
        while (!res.isEmpty()){
            node.next = res.pop();
            node = node.next;
        }
        return dummy.next;
    }
}
    原文作者:greatfulltime
    原文地址: https://www.jianshu.com/p/6b6da9efcac4
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞