原题
题目描述: 给你两个链表,把他们的元素值各自当成一个整数,然后相加得到的值返回一个链表(注:每个节点位置只放一个数字) 思路:
把两个链表压入栈中 若栈不为空,从两个栈中取值,和节点值的三者和,与10的商作为结果链表的值,与10取余,得到的值作为下一个值的进位
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
Stack<Integer> s1=new Stack<Integer>();
Stack<Integer> s2=new Stack<Integer>();
while (l1!=null ){
s1.push(l1.val );
l1=l1.next;
}
while (l2!=null ){
s2.push(l2.val );
l2=l2.next;
}
ListNode newNode=new ListNode(0 );
ListNode cur=newNode;
int sum=0 ;
while (!s1.empty()||(!s2.empty())){
if (!s1.empty()){
sum+=s1.pop();
}
if (!s2.empty()){
sum+=s2.pop();
}
cur.val =sum%10 ;
ListNode head=new ListNode(sum/10 );
head.next=cur;
cur=head;
sum/=10 ;
}
return cur.val ==0 ? cur.next : cur;
}
}