/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
int carry=0; //进位
ListNode pre=new ListNode(0);//伪头节点
ListNode cur=pre;
while(l1!=null||l2!=null){ //注意是l1和l2
int x= l1==null?0:l1.val; //最后为谁null,就置于0
int y=l2==null?0:l2.val;
int sum=x+y+carry; //总和
carry=sum/10; //进位和放置的数
sum%=10;
cur.next=new ListNode(sum);
cur=cur.next; //指针移动
if(l1!=null) l1=l1.next; //此处是if,因为在while里面
if(l2!=null) l2=l2.next;
}
if(carry==1) cur.next=new ListNode(1); //还有进位,则新建
return pre.next;
}
}