You are given two non-empty linked lists representing two non-negative integers. The digits are stored in reverse order and each of their nodes contain a single digit. Add the two numbers and return it as a linked list.
You may assume the two numbers do not contain any leading zero, except the number 0 itself.
Example:
Input: (2 -> 4 -> 3) + (5 -> 6 -> 4) Output: 7 -> 0 -> 8 Explanation: 342 + 465 = 807.
给定两个非空链表来表示两个非负整数。位数按照逆序方式存储,它们的每个节点只存储单个数字。将两数相加返回一个新的链表。
你可以假设除了数字 0 之外,这两个数字都不会以零开头。
示例:
输入:(2 -> 4 -> 3) + (5 -> 6 -> 4) 输出:7 -> 0 -> 8 原因:342 + 465 = 807
题解:此题与之前那道Add Two Numbers II异曲同工,只是这题是原来的两个单链表所表示的数字都是逆序的,同样需要相加后的值也要逆序输出,那么可以利用之前的reverseList算法将这些单链表进行逆序。同样利用大数定理来完成大数加法操作。
public ListNode reverseList(ListNode head)
{
if(head == null || head.next == null)
return head;
ListNode pre = head;
ListNode node = head.next;
while(pre != null && node != null)
{
ListNode temp1 = node.next;
node.next = pre;
if(pre == head)
pre.next = null;
pre = temp1;
if(pre != null)
{
ListNode temp2 = pre.next;
pre.next = node;
node = temp2;
}
}
if(pre == null)
head = node;
else
head = pre;
return head;
}
public ListNode addTwoNumbersII(ListNode l1, ListNode l2)
{
int [] arr1 = new int[100000]; //将第一个单链表存放在数组1中
int [] arr2 = new int[100000]; //将第二个单链表存放在数组2中
int len1 = 0;
int len2 = 0;
int i=0,j=0,k=0;
ListNode p = l1; //定义单链表结点
while( p != null ){ //存储第一个单链表
arr1[i] = p.val ;
i++;
p = p.next;
}
len1 = i;
p = l2;
while( p != null){ //存储第二个单链表
arr2[j] = p.val ;
j++;
p = p.next;
}
len2 = j;
i = len1-1; j=len2-1;
int res[] = new int[Math.max(len1,len2)+1]; //记录两个单链表的和
while(i >= 0 && j >= 0){
res[k] += arr1[i]+arr2[j];
if(res[k]>=10){
res[k+1] = res[k]/10;
res[k] = res[k]%10;
}
k++;
i--;
j--;
}
while(i>=0){ //计算剩余的单链表
res[k] += arr1[i];
if(res[k]>=10){
res[k+1] = res[k]/10;
res[k] = res[k]%10;
}
k++;
i--;
}
while(j>=0){ //计算剩余的单链表
res[k] += arr2[j];
if(res[k]>=10){
res[k+1] = res[k]/10;
res[k] = res[k]%10;
}
k++;
j--;
}
if(res[k] == 0){ //判断最高位是否有进位
k--;
}
ListNode head = new ListNode(0); //定义返回结果的头指针,逆序遍历数组res
if( k>=0 ){
p = new ListNode(res[k]);
head = p;
k--;
}
while(k>=0){ //逆序遍历数组res,将数组用单链表表示
ListNode q = new ListNode(res[k]);
p.next = q;
p = q;
k--;
}
return head;
}
public ListNode addTwoNumbers(ListNode l1,ListNode l2)
{
ListNode newL1 = reverseList(l1);
ListNode newL2 = reverseList(l2);
ListNode newNode = addTwoNumbersII(newL1,newL2);
return reverseList(newNode);
}
最上面的那个reverseList表示对单链表进行反转,也就是逆序;addTwoNumbersII是按照顺序单链表相加的题,可以利用这个方法来对大数进行相加。