LeetCode 2. 【Java】2. Add Two Numbers
原题链接
中等
作者:
tt2767
,
2020-03-05 00:05:49
,
所有人可见
,
阅读 784
/**
1. 和归并排序类似, l1链存储结果, 如果l1 较短就把l2后面接上即可
2. 进位可能多一位, 要在最后new出来
*/
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
if (l1 == null || l2 == null) return l1 == null ? l2 : l1;
int next = 0;
ListNode prev = l1, head = l1;
while (l1 != null && l2 != null){
int sum = l1.val + l2.val + next;
l1.val = sum % 10;
next = sum / 10;
prev = l1;
l1 = l1.next;
l2 = l2.next;
}
if (l2 != null) {
prev.next = l2;
l1 = l2;
}
while (l1 != null && next != 0) {
int sum = l1.val + next;
l1.val = sum % 10;
next = sum / 10;
prev = l1;
l1 = l1.next;
}
if (next != 0) {
prev.next = new ListNode(next);
}
return head;
}
}