LeetCode 2. 两数相加
原题链接
中等
作者:
zjfdlut
,
2020-08-29 20:08:07
,
所有人可见
,
阅读 347
class Solution {
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
int ca = 0;
ListNode head1 = l1;
ListNode head2 = l2;
ListNode dummy = new ListNode(-1);
ListNode dummyHead = dummy;
while(head1 != null || head2 != null){
int n1 = head1 == null ? 0 : head1.val;
int n2 = head2 == null ? 0 : head2.val;
int res = n1 + n2 + ca;
ListNode tmp = new ListNode(res % 10);
dummyHead.next = tmp;
dummyHead = tmp;
if(res > 9){
ca = 1;
}else{
ca = 0;
}
head1 = head1 == null ? null : head1.next;
head2 = head2 == null ? null : head2.next;
}
if(ca == 1){
ListNode tmp = new ListNode(1);
dummyHead.next = tmp;
dummyHead = tmp;
}
return dummy.next;
}
}