2,兩數相加
給定兩個非空連結串列來表示兩個非負整數。位數按照逆序方式儲存,它們的每個節點只儲存單個數字。將兩數相加返回一個新的連結串列。
你可以假設除了數字 0 之外,這兩個數字都不會以零開頭。
示例:
輸入:(2 -> 4 -> 3) + (5 -> 6 -> 4) 輸出:7 -> 0 -> 8 原因:342 + 465 = 807
/**
* 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) {
ListNode dummy=new ListNode(0);
ListNode cur=dummy;
int car=0;
while(l1!=null||l2!=null)
{
int d1=l1==null?0:l1.val;
int d2=l2==null?0:l2.val;
int sum= d1+d2+car;
car=sum>=10?1:0;
cur.next=new ListNode(sum%10);
cur=cur.next;
if(l1!=null) l1=l1.next;
if(l2!=null) l2=l2.next;
}
if(car==1) cur.next=new ListNode(1);
return dummy.next;
}
}