Add Two Numbers
You are given two non-empty linked lists representing two non-negative integers. The digits are stored in reverse order and each of their nodes contain a single digit. Add the two numbers and return it as a linked list.
You may assume the two numbers do not contain any leading zero, except the number 0 itself.
Example:
Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
Explanation: 342 + 465 = 807.
该题给出两个链表,以逆序存储,返回其相加后的结果。其实只要把两个链表依次相加就行了,它所说的逆序只是储存的形式,结果是正序的。例如(3->4->2)+(2->5->6)
结果应该是(5->9->8)而不是(8->9>5),返回的(5->9->8)储存的形式是895所以是正确答案。
建立一个新链表,然后把输入的两个链表从头往后遍历,每两个相加,其中若后面的节点为Null,则默认为0,然后添加一个新节点到新链表后面,注意进位,其中carry维护进位,若两个节点相加大于10,则carry=1,在下一次两个节点相加时还要加上这个carry,同时carry也会重置。注意:最高位的进位在循环结束后还要特殊处理。
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
ListNode dummyHead = new ListNode(0);
ListNode p = l1, q = l2, curr = dummyHead;
int carry = 0;
while (p != null || q != null) {
int x = (p != null) ? p.val : 0;
int y = (q != null) ? q.val : 0;
int sum = carry + x + y;
carry = sum / 10;
curr.next = new ListNode(sum % 10);
curr = curr.next;
if (p != null)
p = p.next;
if (q != null)
q = q.next;
}
if (carry > 0) {
curr.next = new ListNode(carry);
}
return dummyHead.next;
}
下面是稍微修改较简介的版本
public ListNode addTwoNumbers2(ListNode l1, ListNode l2) {
ListNode preHead = new ListNode(0);
ListNode runner = preHead;
int carry = 0;
while (l1 != null || l2 != null || carry != 0) {
if (l1 != null) {
carry += l1.val;
l1 = l1.next;
}
if (l2 != null) {
carry += l2.val;
l2 = l2.next;
}
runner.next = new ListNode(carry % 10);
runner = runner.next;
carry /= 10;
}
return preHead.next;
}