leetcode算法面试题
1.题目
2.代码:
class Solution {
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
ListNode res=new ListNode();
ListNode resTemp=res;
int nextSum=0;
int flag=0;
while(l1!=null&&l2!=null){
int p;
if(flag==0){
p=l1.val+l2.val;
res.val=p%10;
nextSum=p/10;
flag++;
}
else{
p=l1.val+l2.val+nextSum;
resTemp.next=new ListNode(p%10);
resTemp=resTemp.next;
nextSum=p/10;
}
l1=l1.next;
l2=l2.next;
}
while(l1!=null){
int p=l1.val+nextSum;
resTemp.next=new ListNode(p%10);
resTemp=resTemp.next;
nextSum=p/10;
l1=l1.next;
}
while(l2!=null){
int p=(l2.val+nextSum);
resTemp.next=new ListNode(p%10);
resTemp=res.next;
nextSum=p/10;
l2=l2.next;
}
if(nextSum!=0)resTemp.next=new ListNode(nextSum);
return res;
}
}