1.問題描述
給你兩個非空的鏈表府瞄,表示兩個非負(fù)的整數(shù)。它們每位數(shù)字都是按照逆序方式存儲的碘箍,并且每個節(jié)點只能存儲一位數(shù)字遵馆。
請你將兩個數(shù)相加,并以相同形式返回一個表示和的鏈表丰榴。
你可以假設(shè)除了數(shù)字 0 之外货邓,這兩個數(shù)都不會以 0 開頭。
2.測試用例
示例 1:
輸入:l1 = [2,4,3], l2 = [5,6,4]
輸出:[7,0,8]
解釋:342 + 465 = 807.
示例 2:
輸入:l1 = [0], l2 = [0]
輸出:[0]
示例 3:
輸入:l1 = [9,9,9,9,9,9,9], l2 = [9,9,9,9]
輸出:[8,9,9,9,0,0,0,1]
3.補(bǔ)充說明
每個鏈表中的節(jié)點數(shù)在范圍 [1, 100] 內(nèi)
0 <= Node.val <= 9
題目數(shù)據(jù)保證列表表示的數(shù)字不含前導(dǎo)零
4.解題報告
-
遞歸
/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode() {} * ListNode(int val) { this.val = val; } * ListNode(int val, ListNode next) { this.val = val; this.next = next; } * } */ class Solution { public ListNode addTwoNumbers(ListNode l1, ListNode l2) { ListNode currentNode = new ListNode(); int next = 0; currentNode = assignListNode(l1, l2, currentNode, next); return currentNode; } public ListNode assignListNode(ListNode l1, ListNode l2, ListNode currentNode, int next) { if (l1 == null && l2 == null) { if (next > 0) { currentNode.val = 1; } else { currentNode = null; } return currentNode; } int x = l1 == null ? 0 : l1.val; int y = l2 == null ? 0 : l2.val; int sum = x + y + next; currentNode.val = sum % 10; currentNode.next = new ListNode(); currentNode.next = assignListNode(l1 == null ? null : l1.next, l2 == null ? null : l2.next, currentNode.next, sum / 10); return currentNode; } }
-
內(nèi)循環(huán)
public ListNode addTwoNumbers(ListNode l1, ListNode l2) { ListNode dummyHead = new ListNode(0); ListNode p = l1, q = l2, curr = dummyHead; int carry = 0; while (p != null || q != null) { int x = (p != null) ? p.val : 0; int y = (q != null) ? q.val : 0; int sum = carry + x + y; carry = sum / 10; curr.next = new ListNode(sum % 10); curr = curr.next; if (p != null) p = p.next; if (q != null) q = q.next; } if (carry > 0) { curr.next = new ListNode(carry); } return dummyHead.next; }