You are given two linked lists representing two non-negative numbers. 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.
Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
这题意思是,数字是反过来存储在linkedlist里的,比如上面那个其实就是计算
342+465 = 807的过程。
这题最好的解法是programcreek里提供的,利用while()里面的||循环,非常简洁易懂。相比之下code ganker还有其他一些人的解法就繁琐多了,他们的while循环是用&&的,导致需要分别处理l1和l2!=null的情况,非常复杂。以后还是多看几种解法比较好。
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
int carry = 0;
ListNode p1 = l1, p2 = l2, fakeHead = new ListNode(-1), p3 = fakeHead;
while (p1 != null || p2 != null) {
if (p1 != null) {
carry += p1.val;
p1 = p1.next;
}
if (p2 != null) {
carry += p2.val;
p2 = p2.next;
}
p3.next = new ListNode(carry % 10);
p3 = p3.next;
carry = carry / 10;
}
//别忘了
if (carry == 1)
p3.next = new ListNode(carry);
return fakeHead.next;
}
另外,code ganker提到了这题是CC150里的。可以看看。