题目描述
有两个用链表表示的整数,每个结点包含一个数位。这些数位是反向存放的,也就是个位排在链表的首部。编写函数对这两个整数求和,并用链表形式返回结果。
给定两个链表ListNode* A,ListNode* B,请返回A+B的结果(ListNode*)。
测试样例:
{1,2,3},{3,2,1}
返回:{4,4,4}
思路:只要链表还有未处理的节点,或者还有进位(即进位不为0),就进行节点的相加;对于当前指针只想空节点时,使用0代表其值,并且使用null代表下一轮迭代节点。
package niuke;
public class AddList {
public ListNode addList(ListNode A,ListNode B){
ListNode iter1=A,iter2=B;
ListNode list=null,tail=null;
int carry=0;
while(iter1!=null||iter2!=null||carry!=0){
int num1=iter1==null?0:iter1.val;
int num2=iter2==null?0:iter2.val;
int sum=num1+num2+carry;
carry=sum/10;
sum=sum%10;
if(list==null){
list=new ListNode(sum);
tail=list;
}else{
tail.next=new ListNode(sum);
tail=tail.next;
}
iter1=iter1==null?null:iter1.next;
iter2=iter2==null?null:iter2.next;
}
return list;
}
public void showNode(ListNode pHead){
if(pHead==null) return;
int count=0;
while(pHead!=null){
System.out.println("第"+count+"次:"+pHead.val);
pHead=pHead.next;
count++;
}
}
public static void main(String[] args) {
ListNode head=new ListNode(1);
ListNode head1=new ListNode(5);
ListNode head2=new ListNode(4);
ListNode head3=new ListNode(2);
ListNode head4=new ListNode(6);
ListNode head5=new ListNode(7);
head.next =head1;
head1.next=head2;
//head2.next=null;
head3.next=head4;
head4.next=head5;
//head5.next=null;
//System.out.println("shuchu");
AddList pt=new AddList();
ListNode addNode=pt.addList(head, head3);
pt.showNode(addNode);
}
}
结果分析:
第一个链表为1->5->4,即451;
第二个链表为2->6->7,即762;
相加的结果为1213。
第0次:3
第1次:1
第2次:2
第3次:1