题目:用链表模拟两数相加
代码如下
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class Solution {
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
ListNode p=null,head=null,q=null;
ListNode h1=l1,h2=l2;
int flag=0;
while(h1!=null&&h2!=null){
int sum=h1.val+h2.val+flag;
flag=0;
if(sum>=10){
flag=1;
sum%=10;
}
q=new ListNode(sum,null);
if(head==null)head=p=q;
else{
p.next=q;
p=q;
}
h1=h1.next;
h2=h2.next;
}
if(h1==null)h1=h2;
while(h1!=null){
int sum=h1.val+flag;
flag=0;
if(sum>=10){
flag=1;
sum%=10;
}
q=new ListNode(sum,null);
if(head==null)head=p=q;
else{
p.next=q;
p=q;
}
h1=h1.next;
}
if(flag==1){
q=new ListNode(1,null);
if(head==null)head=p=q;
else{
p.next=q;
p=q;
}
}
return head;
}
}