题解 | #两个链表生成相加链表#
两个链表生成相加链表
http://www.nowcoder.com/practice/c56f6c70fb3f4849bc56e33ff2a50b6b
把链表转化呢为数组,然后大数加法
public class Solution {
/**
*
* @param head1 ListNode类
* @param head2 ListNode类
* @return ListNode类
*/
public ListNode addInList (ListNode head1, ListNode head2) {
// write code here
// 把两个链表分别保存到ArrayList 里面,然后执行大数字加法
ArrayList<Integer> num1 = new ArrayList<>();
ArrayList<Integer> num2 = new ArrayList<>();
while(head1 != null){
num1.add(head1.val);
head1 = head1.next;
}
while(head2 != null){
num2.add(head2.val);
head2 = head2.next;
}
// 初始化sum 数组
int sumLen = Math.max(num1.size(),num2.size())+1;
int sumIndex = sumLen -1;
int[] sum = new int[sumLen];
for(int i =0; i < sumLen; i++){
sum[i] = 0;
}
int num1Index =num1.size()-1,num2Index = num2.size()-1;
while(num1Index >=0 && num2Index >=0){
// 求和
int summ = num1.get(num1Index--) + num2.get(num2Index--) + sum[sumIndex];
// 求该位的值
sum[sumIndex--] = summ % 10;
// 求进位
sum[sumIndex] = summ / 10;
}
while(num1Index >=0){
int summ = num1.get(num1Index--) + sum[sumIndex];
// 求该位的值
sum[sumIndex--] = summ % 10;
// 求进位
sum[sumIndex] = summ / 10;
}
while(num2Index >=0){
int summ = num2.get(num2Index--) + sum[sumIndex];
// 求该位的值
sum[sumIndex--] = summ % 10;
// 求进位
sum[sumIndex] = summ / 10;
}
// 把求出来的和拼接为一个链表
if(sum[0] == 0){
ListNode returnHead = new ListNode(1);
ListNode p = returnHead;
for(int j = 1; j<sumLen; j++){
p.next = new ListNode(sum[j]);
p = p.next;
}
return returnHead.next;
}else{
ListNode returnHead = new ListNode(1);
ListNode p = returnHead;
for(int j = 0; j< sumLen; j++){
p.next = new ListNode(sum[j]);
p = p.next;
}
return returnHead.next;
}
}
}