/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
public class Solution {
/**
* @param l1: the first list
* @param l2: the second list
* @return: the sum list of l1 and l2
*/
public ListNode addLists(ListNode l1, ListNode l2) {
// 2015-08-28
if (l1 == null) {
return l2;
}
if (l2 == null) {
return l1;
}
ListNode dummy = new ListNode(0);
ListNode tail = dummy;
int carry = 0; // 进位
while (l1 != null && l2 != null) {
int sum = l1.val + l2.val + carry;
carry = sum / 10;
tail.next = new ListNode(sum % 10);
l1 = l1.next;
l2 = l2.next;
tail = tail.next;
}
while (l1 != null) {
int sum = l1.val + carry;
carry = sum / 10;
tail.next = new ListNode(sum % 10);
l1 = l1.next;
tail = tail.next;
}
while (l2 != null) {
int sum = l2.val + carry;
carry = sum / 10;
tail.next = new ListNode(sum % 10);
l2 = l2.next;
tail = tail.next;
}
if (carry != 0) {
tail.next = new ListNode(carry);
}
return dummy.next;
}
}
[刷题]Add Two Numbers
最新推荐文章于 2022-10-28 16:16:58 发布