You are given two non-empty linked lists representing two non-negative integers. The most significant digit comes first 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.
Follow up:
What if you cannot modify the input lists? In other words, reversing the lists is not allowed.
Example:
Input: (7 -> 2 -> 4 -> 3) + (5 -> 6 -> 4) Output: 7 -> 8 -> 0 -> 7
题意:两个用链表表示十进制数,表头是高位,尾部是低位,求两个数相加,返回和的链表表示。要求不能改变参数链表的结构。
分析:
先计算相同位数的求和,然后计算高位和进位的和,注意细节!
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
int len1=size(l1);
int len2=size(l2);
if(len1<len2){//l1为长链
ListNode temp=l2;
l2=l1;
l1=temp;
}
ListNode result=cloneList(l1);
int len=Math.abs(len1-len2);
ListNode p=result;
for(int i=0;i<len;i++)//让p与l2一样长
p=p.next;
int add=myaddTwoNumbers(p,l2); //两个一样长的链相加,相加结果为p,进位为add
if(add>0&&len>0)
add=myaddNumber(result,len,add);//如果存在进位,让前面多出来的链加上进位。
if(add>0)//最高位有进位,在前面增加节点
{
ListNode node=new ListNode(add);
node.next=result;
result=node;
}
return result;
}
public ListNode cloneList(ListNode list){
ListNode p=list;
ListNode result=null;
ListNode pp=result;
while(p!=null){
if(pp==null)
{
pp=new ListNode(p.val);
result=pp;
}
else
{
pp.next=new ListNode(p.val);
pp=pp.next;
}
p=p.next;
}
return result;
}
public int size(ListNode list){
ListNode p=list;
int size=0;
while(p!=null)
{
p=p.next;
size++;
}
return size;
}
public int myaddNumber(ListNode result,int len,int num){
if(len==1)
{
int temp=result.val+num;
result.val=temp%10;
return temp/10;
}
int add=myaddNumber(result.next,len-1,num);
int temp=result.val+add;
result.val=temp%10;
return temp/10;
}
public int myaddTwoNumbers(ListNode result,ListNode l2){
if(result==null)
return 0;
int add=myaddTwoNumbers(result.next,l2.next);//先计算后面的位,进位为add
int temp=add+result.val+l2.val;
result.val=temp%10;
return temp/10;
}
}