題目描述:
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.
Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
現有兩個非負數的列表。每個節點有一個數字,數字以相反的順序存儲。將對應位置的數字相加,以列表的形式返回。
例如:輸入 243+564,輸出 708.
題目解析:
其實不用考慮別的,就是兩個數字相加,和傳統加法唯一的不同就是此題中的加法是從左往右算的,進位也是從左往右進。
2 4 3
+ 5 6 4
-------------
= 7 0 8
- 正常加法應該先算3+4, 接着4+6,進一位,最後2+5,加之前的進位1,得到8;
- 在本題就應該先算 2+5, 接着4+6,進一位到3+4中,3+4+1=8,最後得到708。
- 對於兩個list不等長的情況,比如1->8 + 0,就把短的list的末尾用0補齊就行了。
- 所以,直接從兩個鏈表中取數相加,添加到新的鏈表即可。要注意兩鏈表全部遍歷完之後,如果還有進位沒有處理,則直接把這個進位添加到新鏈表的最後就行。比如 5 + 5 = 0->1。
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
public class Solution {
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
if (l1 == null) {
return l2;
}
if (l2 == null) {
return l1;
}
ListNode head = new ListNode(0);
ListNode p = head;
int tmp = 0;
while (l1 != null || l2 != null || tmp != 0) {
if (l1 != null) {
tmp = tmp + l1.val;
l1 = l1.next;
}
if (l2 != null) {
tmp = tmp + l2.val;
l2 = l2.next;
}
p.next = new ListNode(tmp % 10);
p = p.next;
tmp = tmp / 10;
}
return head.next;
}
}