LeetCode 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

给了俩链表,要求把两个链表表示的数字加起来。因为要倒着加,所以可以先把链表里所有元素push到stack里然后一个个pop出来。为了生成最终的链表,我们可以先new一个dummy,dummy的右边表示已经生成好的部分,每次产生结果就可以直接new一个新节点,然后令这个新节点的next=dummy。非常简单易懂。但是自己写的时候还是有点小问题:一个是while循环截止条件,我们做这个操作一直到没得加为止,那没得加就是两个list都用完了,并且还没有carry!在while里面处理的时候可以直接,如果stack1不为空就加入stack1.pop,如果stack2不为空就加入stack2.pop,最后加上carry。这题主要是细节问题比较多,时间复杂度O(n)吧。

Runtime: 4 ms, faster than 43.33% of Java online submissions for Add Two Numbers II.

Memory Usage: 39.2 MB, less than 96.37% of Java online submissions for Add Two Numbers II.

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode() {}
 *     ListNode(int val) { this.val = val; }
 *     ListNode(int val, ListNode next) { this.val = val; this.next = next; }
 * }
 */
class Solution {
    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        Deque<Integer> stack1 = new ArrayDeque<>();
        Deque<Integer> stack2 = new ArrayDeque<>();
        
        while (l1 != null) {
            stack1.push(l1.val);
            l1 = l1.next;
        }
        while (l2 != null) {
            stack2.push(l2.val);
            l2 = l2.next;
        }
        
        int carry = 0;
        ListNode dummy = null;
        while (!stack1.isEmpty() || !stack2.isEmpty() || carry != 0) {
            int tempSum = 0;
            if (!stack1.isEmpty()) {
                tempSum += stack1.pop();
            }
            if (!stack2.isEmpty()) {
                tempSum += stack2.pop();
            }
            tempSum += carry;
            carry = tempSum / 10;
            tempSum %= 10;
            
            ListNode newNode = new ListNode(tempSum);
            newNode.next = dummy;
            dummy = newNode;
        }
        return dummy;
    }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值