Question
Solution
题目大意:两个列表相加
思路:构造两个栈,两个列表的数依次入栈,再出栈的时候计算其和作为返回链表的一个节点
Java实现:
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
Stack<Integer> s1 = new Stack<>();
Stack<Integer> s2 = new Stack<>();
while (l1 != null) {
s1.push(l1.val);
l1 = l1.next;
}
while (l2 != null) {
s2.push(l2.val);
l2 = l2.next;
}
ListNode retHead = new ListNode(0);
int pre = 0;
while (!s1.empty() || !s2.empty() || pre > 0) {
int tmp1 = s1.empty() ? 0 : s1.pop();
int tmp2 = s2.empty() ? 0 : s2.pop();
int sum = tmp1 + tmp2 + pre;
pre = sum / 10;
ListNode next = new ListNode(sum % 10);
next.next = retHead.next;
retHead.next = next;
}
return retHead.next;
}