問題: You are given two linked lists representing two non-negative numbers. The digits are stored in reverse order and each of their nodes contain a sin ...
問題:
You are given two linked lists representing two non-negative numbers.
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.
Example:
Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
官方難度:
Medium
翻譯:
現有2個鏈表結構,存儲非0的數字,每個節點的數字都是個位數的而且倒著排序,把這2個鏈表的數字相加並倒序輸出。
例子:
鏈表一:2->4->3
鏈表二:5->6->4
輸出:7->0->8
思路:
1.Java中的鏈表結構,就是LinkedList。
2.Java中的集合迭代器ListIterator,擁有自末尾向前遍歷的特性,在這裡可以運用。
解題中可能遇到的困難:
1.創建ListIterator的時候,指針的位置需要指向鏈表的末尾。
解題代碼:
1 private static List<Integer> method(List<Integer> list1, List<Integer> list2) { 2 int sum1 = 0; 3 int sum2 = 0; 4 int size1 = list1.size(); 5 int size2 = list2.size(); 6 // 聲明2個ListIterator,可以逆向迭代,指針位置先給到最後一位 7 ListIterator<Integer> iter1 = list1.listIterator(size1); 8 ListIterator<Integer> iter2 = list2.listIterator(size2); 9 // 逆序遍歷+累加 10 while (iter1.hasPrevious()) { 11 sum1 += iter1.previous() * Math.pow(10, --size1); 12 } 13 while (iter2.hasPrevious()) { 14 sum2 += iter2.previous() * Math.pow(10, --size2); 15 } 16 int sum = sum1 + sum2; 17 List<Integer> resultList = new LinkedList<>(); 18 while (sum > 0) { 19 // 取末尾 20 resultList.add(sum % 10); 21 // 去末尾 22 sum /= 10; 23 } 24 return resultList; 25 }View Code
測試代碼地址:
https://github.com/Gerrard-Feng/LeetCode/blob/master/LeetCode/src/com/gerrard/algorithm/medium/Q002.java
LeetCode題目地址:
https://leetcode.com/problems/add-two-numbers/
PS:如有不正確或提高效率的方法,歡迎留言,謝謝!