445. Add Two Numbers II 链表中的数字求和

[抄题]:

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

 [暴力解法]:

时间分析:

空间分析:

 [优化后]:

时间分析:

空间分析:

[奇葩输出条件]:

[奇葩corner case]:

最后看第一位是不是0,不是0才能返回。

[思维问题]:

顺序是反的,不知道用stack

通过sum / 10的方法可以把十位取出来,不用清空,每次除10一直加就行了

[英文数据结构或算法,为什么不用别的数据结构或算法]:

[一句话思路]:

顺序是反的就要用stack求和

[输入量]:空: 正常情况:特大:特小:程序里处理到的特殊情况:异常情况(不合法不合理的输入):

[画图]:

[一刷]:

  1. 先初始化一个待添加列表list,然后余数都往后面加。求和的头都放在head中。

[二刷]:

  1. list.val = sum % 10; 可以直接往用等号list后面加点,不知道怎么来的

[三刷]:

[四刷]:

[五刷]:

  [五分钟肉眼debug的结果]:

[总结]:

通过sum / 10的方法可以把十位取出来,不用清空,每次除10一直加就行了。倒序相加用stack

[复杂度]:Time complexity: O(n) Space complexity: O(n)

[算法思想:迭代/递归/分治/贪心]:

[关键模板化代码]:

[其他解法]:

[Follow Up]:

[LC给出的题目变变变]:

 [代码风格] :

 [是否头一次写此类driver funcion的代码] :

 [潜台词] :

 

/**
 * 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) {
        //initialization: 2 stacks
        Stack<Integer> stack1 = new Stack<Integer>();
        Stack<Integer> stack2 = new Stack<Integer>();
        
        //corner case
        if (l1 == null && l2 == null) return null; 
        
        //put into stacks
        while (l1 != null) {
            stack1.add(l1.val);
            l1 = l1.next;
        }
        
        while (l2 != null) {
            stack2.add(l2.val);
            l2 = l2.next;
        }
        
        //while loop
        //get sum, val, head, append the previous val to head, give head to val, reset sum
        ListNode list = new ListNode(0);
        int sum = 0;
        while (!stack1.isEmpty() || !stack2.isEmpty()) {
            //get sum
            if (!stack1.isEmpty()) sum += stack1.pop();
            if (!stack2.isEmpty()) sum += stack2.pop();
            
            //get the val node
            list.val = sum % 10;
            
            ListNode head = new ListNode(sum / 10);
            //append the previous val to head, head is ready
            head.next = list;
            //give head to val
            list = head;
            
            sum /= 10;
        }
        
        //return
        return list.val == 0 ? list.next : list;
    }
}
View Code

 

转载于:https://www.cnblogs.com/immiao0319/p/9401567.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值