class ListNode{
//创建节点类
int val;
ListNode next;
ListNode(int x) {
this.val = x;
}
}
class Solution {
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
ListNode dummy=new ListNode(0);//创建哑节点
ListNode cur=dummy;//"现在"指针指向头节点
int carry=0;//初始进位为零
while(l1!=null||l2!=null) {
int x=(l1==null)?0:l1.val;//遍历完l之后x即为0;
int y=(l2==null)?0:l2.val;
int sum=x+y+carry;//加上进位就是当前节点的值
carry=sum/10;//carry只有可能是0和1
sum=sum%10;//实际的只要个位上的值
cur.next=new ListNode(sum);
cur=cur.next;//将当前指针后移;
if(l1!=null)l1=l1.next;//若非空就将指针向后移
if(l2!=null)l2=l2.next;
}
if(carry==1) {
cur.next=new ListNode(1);
}//当两条节点都遍历之后,根据最终的carry值来确定最高位的数字
return dummy.next;//返回结果的头节点
}
}
}
思路来自评论区:灵魂画师牧马