给你两个 非空 链表来代表两个非负整数。数字最高位位于链表开始位置。它们的每个节点只存储一位数字。将这两数相加会返回一个新的链表。
你可以假设除了数字 0 之外,这两个数字都不会以零开头。
示例:
输入:(7 -> 2 -> 4 -> 3) + (5 -> 6 -> 4) 输出:7 -> 8 -> 0 -> 7
解题思路: 使用两个栈,将两个链表存起来,然后再依次取出进行相加,采用头插法把相加的结果插入链表,返回。
class Solution {
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
Stack<Integer> s1 = buildStack(l1);
Stack<Integer> s2 = buildStack(l2);
int carry = 0;
ListNode head = new ListNode(-1);
while(!s1.isEmpty() || !s2.isEmpty() || carry!=0){
int tmp1 = s1.isEmpty()?0:s1.pop();
int tmp2 = s2.isEmpty()?0:s2.pop();
int val = tmp1+tmp2+carry;
ListNode tmp = new ListNode(val % 10);
tmp.next = head.next;
head.next = tmp;
carry = val/10;
}
return head.next;
}
public Stack<Integer> buildStack(ListNode l){
Stack<Integer> tmp = new Stack<>();
while(l != null){
tmp.push(l.val);
l = l.next;
}
return tmp;
}
}