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;
    }
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容