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.
Input: (2 -> 4 -> 3) + (5 -> 6 -> 4) Output: 7 -> 0 -> 8
拿到題目,我的第一個思路是這樣的:
兩個鏈表,當鏈表均不為空時,將鏈表push到棧中,然后同時pop出來,計算棧中數字之和;計算完成后,判斷將和對10求余數,放到結果的頭結點中,然后把商push到棧中,然后將原始兩個鏈表的值的next賦值為原來的兩個鏈表。
如此遞歸,即可求出最終值。
不過這里面的判斷方式有些問題,比如遞歸的條件,應該是棧不為空,或者原始的兩個鏈表不為空。
寫的代碼比較冗余,就不獻丑了。
現在貼出贊比較多的一個解。
public static ListNode addTwoNumbers(ListNode l1, ListNode l2) { ListNode prev = new ListNode(0); ListNode head = prev; int carry = 0; while (l1 != null || l2 != null || carry != 0) { ListNode cur = new ListNode(0); int sum = ((l2 == null) ? 0 : l2.val) + ((l1 == null) ? 0 : l1.val) + carry; cur.val = sum % 10; carry = sum / 10; prev.next = cur; prev = cur; l1 = (l1 == null) ? l1 : l1.next; l2 = (l2 == null) ? l2 : l2.next; } return head.next;}這里沒有使用到棧的概念,增加了一個carry,也就是表示商。同時,這里面有個概念,java到底是傳值和傳引用,這里的head和prev就是這樣。
新聞熱點
疑難解答