题解 | #链表相加(二)#
链表相加(二)
https://www.nowcoder.com/practice/c56f6c70fb3f4849bc56e33ff2a50b6b
import java.util.*;
/*
* public class ListNode {
* int val;
* ListNode next = null;
* }
*/
public class Solution {
/**
*
* @param head1 ListNode类
* @param head2 ListNode类
* @return ListNode类
*/
public ListNode addInList(ListNode head1, ListNode head2) {
Stack<Integer> s1=new Stack<>();
Stack<Integer> s2=new Stack<>();
//将链表都加入到栈中
while (head1!=null){
s1.push(head1.val);
head1=head1.next;
}
while (head2!=null){
s2.push(head2.val);
head2=head2.next;
}
int n1=0;
int n2=0;
int n=0;
int ca=0;
ListNode pre=null;
ListNode node=null;
//从栈中取出数据进行相加
while (!s1.isEmpty() || !s2.isEmpty()) {
n1=s1.isEmpty()?0:s1.pop();
n2=s2.isEmpty()?0:s2.pop();
n=n1+n2+ca;
pre=node;
node=new ListNode(n%10);
node.next=pre;
ca=n/10;
}
//说明有进位数
if (ca>0){
//有进位说明了要加一
pre=node;
node=new ListNode(ca);
node.next=pre;
}
return node;
}
}

