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
拿到題目,我的第一個(gè)思路是這樣的:
兩個(gè)鏈表,當(dāng)鏈表均不為空時(shí),將鏈表push到棧中,然后同時(shí)pop出來(lái),計(jì)算棧中數(shù)字之和;計(jì)算完成后,判斷將和對(duì)10求余數(shù),放到結(jié)果的頭結(jié)點(diǎn)中,然后把商push到棧中,然后將原始兩個(gè)鏈表的值的next賦值為原來(lái)的兩個(gè)鏈表。
如此遞歸,即可求出最終值。
不過(guò)這里面的判斷方式有些問(wèn)題,比如遞歸的條件,應(yīng)該是棧不為空,或者原始的兩個(gè)鏈表不為空。
寫(xiě)的代碼比較冗余,就不獻(xiàn)丑了。
現(xiàn)在貼出贊比較多的一個(gè)解。
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;}這里沒(méi)有使用到棧的概念,增加了一個(gè)carry,也就是表示商。同時(shí),這里面有個(gè)概念,java到底是傳值和傳引用,這里的head和prev就是這樣。
新聞熱點(diǎn)
疑難解答
圖片精選
網(wǎng)友關(guān)注