LeetCode第二題
阿新 • • 發佈:2018-11-16
題目:
You are given two non-empty linked lists representing two non-negative integers. The digits are stored in reverse order and each of their nodes contain a single digit. Add the two numbers and return it as a linked list.
You may assume the two numbers do not contain any leading zero, except the number 0 itself.
Example:
Input: (2 -> 4 -> 3) + (5 -> 6 -> 4) Output: 7 -> 0 -> 8 Explanation: 342 + 465 = 807.
思路:
1)由於兩個連結串列的長度不一定相同,而且有可能有空,所以首先應該先排除空連結串列情況
2)我習慣解決問題是由特例到一般,即先考慮最特殊的情況,再推出最普遍一般的情況。
a. 兩個連結串列都只有一個節點時,只需計算和,判斷值是否>10 ,是則進位,否則以該值建立單節點連結串列即可。
b. 當兩個連結串列都不只一個節點則需要考慮雙方後續節點是否為null,在這裡我將判斷是否null 和進位融合在一起,當判斷前一位相加的和>10 後,若next不為空則next.val++。
c. 迭代addTwoNumbers(l1.next,l2.next)。
/** * 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) { if(l1 == null) l1 = new ListNode(0); if(l2 == null) l2 = new ListNode(0); if(l1.next == null && l2.next == null){ int val = l1.val + l2.val; if(val > 9){ int geWei = val%10; ListNode node = new ListNode(geWei); int shiWei = val/10; node.next = new ListNode(shiWei); return node; }else return new ListNode(val); }else{ int val = l1.val + l2.val; if(val > 9){ val = val - 10; if(l1.next != null) l1.next.val++; else if (l2.next != null) l2.next.val++; } ListNode node = new ListNode (val); node.next = addTwoNumbers(l1.next,l2.next); return node; } } }