题目描述:
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;
}
}