有关于我
我的生活
这个网站
刷题之旅
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 Solution:
/**
* 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> st1 = new ArrayDeque();
Deque<Integer> st2 = new ArrayDeque();
while (l1 != null) {
st1.push(l1.val);
l1 = l1.next;
}
while (l2 != null) {
st2.push(l2.val);
l2 = l2.next;
}
ListNode prev = null;
int carry = 0;
while (!st1.isEmpty() && !st2.isEmpty()) {
int a = st1.pop();
int b = st2.pop();
int val = (a + b + carry) % 10;
carry = (a + b + carry) / 10;
ListNode curr = new ListNode(val);
curr.next = prev;
prev = curr;
}
while (!st1.isEmpty()) {
int a = st1.pop();
int val = (a + carry) % 10;
carry = (a + carry) / 10;
ListNode curr = new ListNode(val);
curr.next = prev;
prev = curr;
}
while (!st2.isEmpty()) {
int a = st2.pop();
int val = (a + carry) % 10;
carry = (a + carry) / 10;
ListNode curr = new ListNode(val);
curr.next = prev;
prev = curr;
}
if (carry != 0) {
ListNode curr = new ListNode(carry);
curr.next = prev;
prev = curr;
}
return prev;
}
}
Please enable JavaScript to view the comments