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è)非負(fù)整數(shù)。 數(shù)字以相反的順序存儲(chǔ),并且它們的每個(gè)節(jié)點(diǎn)包含單個(gè)數(shù)字。 添加兩個(gè)數(shù)字并將其作為鏈接列表返回。
您可以假定這兩個(gè)數(shù)字不包含任何前導(dǎo)零,除了數(shù)字0本身。
輸入:(2→4→3)+(5→6→4) 輸出:7 - > 0 - > 8
代碼:
/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { val = x; } * } */public class Solution { public ListNode addTwoNumbers(ListNode l1, ListNode l2) { ListNode node = new ListNode(0); if(l1 == null && l2 == null) return l1; back(node, l1, l2); return node; } public void back(ListNode result, ListNode l1, ListNode l2){ if(l1 != null) result.val += l1.val; else l1 = new ListNode(0); if(l2 != null) result.val += l2.val; else l2 = new ListNode(0); ListNode node = new ListNode(0); if(result.val >= 10){//說明會(huì)下一個(gè)節(jié)點(diǎn)值至少為1 result.val = result.val % 10; node.val = 1; result.next = node; } if( (l1.next != null || l2.next != null)){ result.next = node; back(result.next, l1.next, l2.next); } }}新聞熱點(diǎn)
疑難解答
圖片精選
網(wǎng)友關(guān)注