假設這些數位是正向存放的。node
LinkedListNode addLists(LinkedListNode l1, LinkedListNode l2, int carry)
{
/*兩個鏈表所有都爲空且進位爲0,則函數返回*/
if (l1 == null &&l2 == null&&carry == 0)
{
return null;
}
LinkedListNode result = new LinkedListNode();
/*將value以及l1和l2的data相加*/
int value = carry;
if (l1 != null)
{
value += l1.data;
}
if (l2 != null)
{
value += l2.data;
}
result.data = value % 10;/*求和結果的個數*/
/*遞歸*/
LinkedListNode more = addLists(l1==null?null:l1.next,l2==null?null:l2.next,value>=10?1:0);
result.setNext(more);
return result;
}函數
在實現這段代碼時,務必注意處理一個鏈表比另外一個鏈表結點少的狀況。否則可能會出現指針異常。指針
進階遞歸
public class PartialSum
{
public LinkedListNode sum=null;
public int carry=0;
}
LinkedListNode addLists(LinkedListNode l1,LinkedListNode l2)
{
int len1=length(l1);
int len2=length(l2);
//用零填充較短的鏈表
if(len1<len2)
{
l1=padList(l1,len2-len1);
}
else
{
l2=padList(l2,len1-len2);
}
//對兩個鏈表求和
PartialSum sum=addListsHelper(l1,l2);
//若有進位,則插入鏈表首部,不然,直接返回整個鏈表
if(sum.carry==0)
{
return sum.sum;
}
else
{
LinkedListNode result=insertBefore(sum.sum,sum.carry);
return result;
}
}
PartialSum addListsHelper(LinkedListNode l1,LinkedListNode l2)
{
if(l1==null && l2==null)
{
PartialSum sum=new PartialSum();
return sum;
}
//對較小數字遞歸求和
PartialSum sum=addListHelper(l1.next,l2.next);
//將進位和當前數據相加
int val=sum.carry +l1.data+l2.data;
//插入當前數字的求和結果
LinkedListNode full_result=insertBefore(sum.sum,val%10);
//返回求和結果和進位值
sum.sum=full_result;
sum.carry=val/10;
return sum;
}
//用零填充鏈表
LinkedListNode padList(LinkedListNode l,int padding)
{
LinkedListNode head=l;
for(int i=0;i<padding;i++)
{
LinkedListNode n=new LinkedListNode(0,null,null);
head.prev=n;
n.next=head;
head=n;
}
return head;
}
//輔助函數,將結點插入鏈表首部
LinkedListNode insertBefore(LinkedListNode list,int data)
{
LinkedListNode node=new LinkedListNode(data,null,null);
if(list!=null)
{
list.prev=node;
node.next=list;
}
return node;
}class