题解 | #链表相加(二)#
链表相加(二)
http://www.nowcoder.com/practice/c56f6c70fb3f4849bc56e33ff2a50b6b
链表 1 为 9->3->7,链表 2 为 6->3,最后生成新的结果链表为 1->0->0->0。
import java.util.LinkedList;
/*
思路:使用栈的思想,将两数相加之后,重新创建新的链表,进行头插
*/
public class Solution {
public ListNode addInList (ListNode head1, ListNode head2) {
//创建两个栈
Deque<Integer> stack1 = new LinkedList<Integer>();
Deque<Integer> stack2 = new LinkedList<Integer>();
//分别入栈
while(head1!=null){
stack1.push(head1.val);
head1=head1.next;
}
while (head2!=null){
stack2.push(head2.val);
head2=head2.next;
}
int sum = 0;
//进位
int carry =0;
ListNode ans=null;
while(!stack1.isEmpty()||!stack2.isEmpty()||carry>0){
//判断是否为空,不为空,弹栈,为空取0;
int num1 = stack1.isEmpty()?0:stack1.pop();
int num2 = stack2.isEmpty()?0:stack2.pop();
sum=num1+num2+carry;
carry=sum/10;
ListNode head = new ListNode(sum%10);
//头插法
head.next=ans;
ans=head;
}
return ans;
}
}