You are given two non-empty linked lists representing two non-negative integers. The most significant digit comes first 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.
Follow up:
What if you cannot modify the input lists? In other words, reversing the lists is not allowed.
Example:
Input: (7 -> 2 -> 4 -> 3) + (5 -> 6 -> 4) Output: 7 -> 8 -> 0 -> 7
給定兩個鏈表,其中每個鏈表都代表一個數字,如:(7 -> 2 -> 4 -> 3) =7243,輸出將兩個鏈表相加的結果,以鏈表方式表示(但不能倒反節點進行操作)
題解
如下例:
| 元素 |
鏈表1 | 1->2->3->4 |
鏈表2 | 9->9->9->9->9 |
- 歷遍兩個鏈表,得出兩個鏈表的長度
| 元素 | 長度 |
鏈表1 | 9->9->9->9->9 | 5 |
鏈表2 | 1->2->3->4 | 4 |
- 比較兩個鏈表的長度,若鏈表2的長度大於鏈表1,則交換彼此
| 元素 | 長度 |
鏈表1 | 9->9->9->9->9 | 5 |
鏈表2 | 1->2->3->4 | 4 |
- 將鏈表1的指針指到鏈表2頭指針的首位數的位置
9->*9->9->9->9
*1->2->3->4 *指針
- 對鏈表1與2進行每一位數的相加(相加在表1上)
9->10->11->12->13
1->2->3->4
- 對鏈表1除了第一個節點(第1位數),其他位數節點進行進位操作(反覆檢查至每一位都有進行進位)
10->1->2->3->3
- 檢查第一位是否大於9,有則進行進位操作(在第一個節點前面加一個節點),若不用進行進位操作則返回第1個節點
1->0->1->2->3->3
- 若第1位進行進位操作,則返回最新添加的節點
package LeetCode.Medium;
import LeetCode.Dependencies.ListNode;
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
public class AddTwoNumbersII {
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
ListNode result = null;
if(l1 == null || l2 == null)
return result;
//得到兩個鏈表的長度
int l1len = getLength(l1);
int l2len = getLength(l2);
//若l2長度大於l1的長度,就交換它們
if(l2len > l1len) {
ListNode tmp = l2;
l2 = l1;
l1 = tmp;
int lenTmp = l2len;
l2len = l1len;
l1len = lenTmp;
}
//設置l1的頭指針
ListNode l1head = l1;
//將l1的指針與l2的頭指針進行對齊,以方便相加
int moveStep = l1len - l2len;
for(int i = 0; i < moveStep; i ++) {
l1 = l1.next;
}
//將l1與l2相加
while(l1 != null && l2 != null) {
l1.val += l2.val;
l1 = l1.next;
l2 = l2.next;
}
//處理第一位之後的進位,並檢查每一位都有確實進位
boolean needCheck = true;
while(needCheck == true) {
l1 = l1head;
needCheck = false;
while(l1 != null) {
if(l1.next != null) {
if(l1.next.val > 9) {
l1.next.val = l1.next.val % 10;
l1.val += 1;
needCheck = true;
}
}
l1 = l1.next;
}
}
//處理第一位進位,若第一位需要進位則在前面多一個節點
l1 = l1head;
if(l1.val > 9) {
ListNode head = new ListNode(1);
l1.val = l1.val % 10;
head.next = l1;
return head;
}
return l1;
}
int getLength(ListNode list) {
int length = 0;
while(list != null) {
length ++;
list = list.next;
}
return length;
}
}