您的位置:首页 > 编程语言 > Java开发

leetcode445 Add Two Numbers II java

2017-03-11 10:38 351 查看

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:

Input: (7 -> 2 -> 4 -> 3) + (5 -> 6 -> 4)

Output: 7 -> 8 -> 0 -> 7

解法

用栈可以很方便解决。

public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
Stack<Integer> stack1 = new Stack<>();
Stack<Integer> 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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  leetcode java