Description
https://leetcode.com/problems/add-two-numbers-ii/
题目大意:
给定两个非空链表,表示两个非负整数,每个结点包含一个数字。对这两个非负整数求和并将其作为链表返回。除了数字0本身,这两个非负整数不包含前导0。要求不修改原列表。
Input: (7 -> 2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 8 -> 0 -> 7
Explanation: 7243 + 564 = 7807.
Solving Ideas
使用两个辅助栈
Solution
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
import java.util.LinkedList;
class Solution {
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
LinkedList<Integer> stack1 = new LinkedList<>();
LinkedList<Integer> stack2 = new LinkedList<>();
while (l1 != null) {
stack1.push(l1.val);
l1 = l1.next;
}
while (l2 != null) {
stack2.push(l2.val);
l2 = l2.next;
}
ListNode head = new ListNode(0);
while (!stack1.isEmpty() || !stack2.isEmpty()) {
if (!stack1.isEmpty()) head.val += stack1.pop();
if (!stack2.isEmpty()) head.val += stack2.pop();
ListNode node = new ListNode(head.val / 10);
head.val %= 10;
node.next = head;
head = node;
}
return head.val == 0 ? head.next : head;
}
}