鏈表表示的兩數相加
阿新 • • 發佈:2018-08-30
add lse style first dtw number span bsp 節點
給定兩個非空鏈表來表示兩個非負整數。位數按照逆序方式存儲,它們的每個節點只存儲單個數字。將兩數相加返回一個新的鏈表。你可以假設除了數字 0 之外,這兩個數字都不會以零開頭。
示例:
輸入:(2 -> 4 -> 3) + (5 -> 6 -> 4)
輸出:7 -> 0 -> 8
原因:342 + 465 = 807
代碼一:
1 public ListNode addTwoNumbers(ListNode l1, ListNode l2) { 2 ListNode result = new ListNode(0); 3 ListNode first = l1, second = l2, tmpNode = result;4 int tmp = 0; 5 6 while(first != null || second != null){ 7 int firstValue ,secondValue; 8 if(first == null){firstValue = 0;} 9 else{firstValue = first.val;} 10 11 if(second == null){secondValue = 0;} 12 else{secondValue = second.val;} 13 14 tmp = tmp + firstValue + secondValue; 15 tmpNode.next = new ListNode(tmp % 10); 16 tmp = tmp / 10; 17 18 tmpNode = tmpNode.next; 19 if(first != null){first = first.next;} 20 if(second != null){second = second.next;} 21 } 22 if(tmp != 0){ 23 tmpNode.next = new ListNode(tmp % 10); 24 } 25 return result.next; 26 }
代碼二:
1 public ListNode addTwoNumbers(ListNode l1, ListNode l2) { 2 ListNode dummyHead = new ListNode(0); 3 ListNode p = l1, q = l2, curr = dummyHead; 4 int carry = 0; 5 while (p != null || q != null) { 6 int x = (p != null) ? p.val : 0; 7 int y = (q != null) ? q.val : 0; 8 int sum = carry + x + y; 9 carry = sum / 10; 10 curr.next = new ListNode(sum % 10); 11 curr = curr.next; 12 if (p != null) p = p.next; 13 if (q != null) q = q.next; 14 } 15 if (carry > 0) { 16 curr.next = new ListNode(carry); 17 } 18 return dummyHead.next; 19 }
鏈表表示的兩數相加