Leetcode 2. 两数相加
链表基本操作,模拟进位
class Solution {
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
ListNode l1p, l2p, head = new ListNode(), temp = head;
int add = 0;
while (true) {
//模拟进位
if (l1 != null) {
add += l1.val;
l1 = l1.next;
}
if (l2 != null) {
add += l2.val;
l2 = l2.next;
}
temp.next = new ListNode(add % 10);
add /= 10;
//指向下一个位置并判断是否加完
temp = temp.next;
if (l1 == null && l2 == null) {
if (add != 0) temp.next = new ListNode(add);
break;
}
}
return head.next;
}
}