Question
Solution
题目大意:两个链表对应的元素相加,满10进1,反两个链表相加后的链表
思路:同时遍历两个链表,同时构造相加后的链表,满10进1,用一个数来记录进位
Java实现:
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
ListNode ans = new ListNode(0);
ListNode curL1 = l1;
ListNode curL2 = l2;
ListNode curAns = ans;
int last = 0;
ListNode curAnsPre = ans;
while (curL1 != null || curL2 != null) {
int valL1 = 0;
int valL2 = 0;
if (curL1 != null) {
valL1 = curL1.val;
curL1 = curL1.next;
}
if (curL2 != null) {
valL2 = curL2.val;
curL2 = curL2.next;
}
curAns.val = valL1 + valL2 + last;
if (curAns.val >= 10) {
curAns.val -= 10;
last = 1;
} else {
last = 0;
}
curAns.next = new ListNode(1);
curAnsPre = curAns;
curAns = curAns.next;
}
curAnsPre.next = last == 0 ? null : curAnsPre.next;
return ans;
}