int[] arr1=new int[]{1,4,3};
int[] arr2=new int[]{5,6,4};
ListNode node1=new ListNode(-1);
ListNode p=node1;
ListNode node2=new ListNode(-1);
ListNode q=node2;
ListNode t=null;
for(int i:arr1){
t=new ListNode(i);
p.next=t;
p=t; #注意写法,这样写是尾插法,尾插法对不是头插法
// p=p.next;
// System.out.println(t);
}
for(int i:arr2){
t=new ListNode(i);
q.next=t;
q=t;
// q=q.next;
}
// System.out.println(p);
ListNode h=addTwoList(node1, node2);
while(h!=null){
System.out.println(h.val);
h=h.next;
// System.out.println(h);
}
}
public static ListNode addTwoList(ListNode node1,ListNode node2){
ListNode p=node1,q=node2;
ListNode dummy=new ListNode(-1);
ListNode h=dummy;
ListNode m=null;
int flag=0;
while(p!=null&&q!=null){
int res=p.val+q.val+flag;
if(res>9){
flag=1;
res=res%10;
}else{
flag=0;
}
m=new ListNode(res);
p=p.next;
q=q.next;
h.next=m;
h=m;
System.out.println(h);
}
while(p!=null){
int res=p.val+flag;
if(res>9){
flag=1;
res=res%10;
}else{
flag=0;
}
m=new ListNode(res);
p=p.next;
h.next=m;
h=m;
}
while(q!=null){
int res=q.val+flag;
if(res>9){
flag=1;
res=res%10;
}else{
flag=0;
}
m=new ListNode(res);
q=q.next;
h.next=m;
h=m;
}
return dummy;
}