Description 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:
【leetcode445 Add Two Numbers II java】Input: (7 -> 2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 8 -> 0 -> 7
解法 用栈可以很方便解决。
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
Stack stack1 = new Stack<>();
Stack stack2 = new Stack<>();
while(l1 != null) {
stack1.push(l1.val);
l1 = l1.next;
}
while(l2 != null) {
stack2.push(l2.val);
l2 = l2.next;
}
ListNode result = new ListNode(0);
int carry = 0;
while(!(stack1.isEmpty() && stack2.isEmpty())) {
int num1 = stack1.isEmpty() ? 0 : stack1.pop();
int num2 = stack2.isEmpty() ? 0 : stack2.pop();
result.val = (num1 + num2 + carry) % 10;
carry = (num1 + num2 + carry) / 10;
ListNode head = new ListNode(carry);
head.next = result;
result = head;
}
return result.val == 0 ? result.next : result;
}
推荐阅读
- 数据结构与算法|【算法】力扣第 266场周赛
- leetcode|今天开始记录自己的力扣之路
- Python|Python 每日一练 二分查找 搜索旋转排序数组 详解
- 【LeetCode】28.实现strstr() (KMP超详细讲解,sunday解法等五种方法,java实现)
- LeetCode-35-搜索插入位置-C语言
- leetcode python28.实现strStr()35. 搜索插入位置
- Leetcode Permutation I & II
- python|leetcode Longest Substring with At Most Two Distinct Characters 滑动窗口法
- LeetCode 28 Implement strStr() (C,C++,Java,Python)
- Python|Python Leetcode(665.非递减数列)