給定兩個非空鏈表來表示兩個非負整數。位數按照逆序方式存儲,它們的每一個節點只存儲單個數字。將兩數相加返回一個新的鏈表。spa
你能夠假設除了數字 0 以外,這兩個數字都不會以零開頭。code
示例:blog
輸入:(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 c1 = l1; ListNode c2 = l2; ListNode sentinel = new ListNode(0); ListNode d = sentinel; int sum = 0; while (c1 != null || c2 != null) { sum /= 10; if (c1 != null) { sum += c1.val; c1 = c1.next; } if (c2 != null) { sum += c2.val; c2 = c2.next; } d.next = new ListNode(sum % 10); d = d.next; } if (sum / 10 == 1) d.next = new ListNode(1); return sentinel.next; } }