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
class Solution {
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
Stack<ListNode> stack1 = new Stack<>();
Stack<ListNode> stack2 = new Stack<>();
ListNode answer = null;
while(l1 != null){
stack1.push(l1);
l1 = l1.next;
}
while(l2 != null){
stack2.push(l2);
l2 = l2.next;
}
int a = 0, b = 0, carry = 0, left = 0;
while(!stack1.isEmpty() || !stack2.isEmpty()){
if(!stack1.isEmpty()) {a = stack1.pop().val;}
else {a = 0;}
if(!stack2.isEmpty()) {b = stack2.pop().val;}
else {b = 0;}
left = (a + b + carry) % 10;
carry = (a + b + carry) / 10;
ListNode p = new ListNode(left);
p.next = answer;
answer = p;
}
if(carry != 0){
ListNode p = new ListNode(carry);
p.next = answer;
answer = p;
}
return answer;
}
}
网友评论