题解 | #链表相加(二)#
链表相加(二)
http://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) {
// write code here
Deque<Integer> keep1 = new LinkedList<Integer>();
Deque<Integer> keep2 = new LinkedList<Integer>();
ListNode head = new ListNode(-1);
//初始化栈
while(head1!=null){
keep1.offerLast(head1.val);
head1 = head1.next;
}
while(head2!=null){
keep2.offerLast(head2.val);
head2 = head2.next;
}
//开始计算,count保存进位
int count = 0;
while(!keep1.isEmpty() && !keep2.isEmpty()){
int a = keep1.pollLast();
int b = keep2.pollLast();
int sum = a+b+count;
count = sum / 10;
ListNode tmp = new ListNode(sum%10);
tmp.next = head.next;
head.next = tmp;
}
//余值计算
Deque<Integer> keep = keep1.isEmpty()?keep2:keep1;
while(!keep.isEmpty()){
int t = keep.pollLast();
int sum = t+count;
count = sum / 10;
ListNode tmp = new ListNode(sum%10);
tmp.next = head.next;
head.next = tmp;
}
//最后的进位判断
if(count!=0){
ListNode tmp = new ListNode(1);
tmp.next = head.next;
head.next = tmp;
}
return head.next;
}
}