给你两个 非空 链表来代表两个非负整数。数字最高位位于链表开始位置。它们的每个节点只存储一位数字。将这两数相加会返回一个新的链表。
你可以假设除了数字 0 之外,这两个数字都不会以零开头。

思路:因为它是从高位数开始数,我们一般算术从个位数开始加,所以我们需要用栈的数据结构来解决这个问题
class Solution {
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
Deque<Integer> d1=new LinkedList<>();
Deque<Integer> d2=new LinkedList<>();
while(l1!=null){
d1.push(l1.val);
l1=l1.next;
}
while(l2!=null){
d2.push(l2.val);
l2=l2.next;
}
ListNode head=new ListNode();
int carry=0;
while(!d1.isEmpty()||!d2.isEmpty()||carry==1){
int a=d1.isEmpty()?0:d1.pop();
int b=d2.isEmpty()?0:d2.pop();
int cur=a+b+carry;
carry=0;
if(cur>9){
cur=cur%10;
carry=1;
}
ListNode node1=new ListNode(cur);
node1.next=head.next;
head.next=node1;
}
return head.next;
}
}









