题目链接https://leetcode-cn.com/problems/add-two-numbers/
/**
* 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) {
/*
* 正常加法向左进位,大于10,当前位为0,向左进1。
* 此题反向。大于10,当前为0,向右进1.
*/
ListNode newnode=new ListNode(0);
ListNode p1=l1;
ListNode p2=l2;
ListNode pnew=newnode;
int carry=0;//进位变量。
while(p1!=null||p2!=null) {
/*
* 长度不相同时
* 1 2 3 这里模拟一个0
* (1 2 3 0)
* +
* 9 2 4 5
* =
* 0 5 7 5
*/
int x=(p1!=null)?p1.val:0;
int y=(p2!=null)?p2.val:0;
int sum=x+y+carry;
carry=sum/10;
pnew.next=new ListNode(sum%10);
pnew=pnew.next;
if(p1!=null) {
p1=p1.next;
}
if(p2!=null) {
p2=p2.next;
}
}
//当链表遍历完的时候突然进位了1的情况,那就要多加以一位。
//例如a:1 1 9 b:1 1 1
//两个链表都遍历完了,得出结果是2 2 0 ,但是还多出了个1,所以就得在链表末尾补上
//结果2 2 0 1
if(carry>0) {
pnew.next=new ListNode(1);//carry不是0就是1
}
return newnode.next;
}
}