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
這題意思是句葵,數(shù)字是反過來存儲在linkedlist里的恨诱,比如上面那個其實就是計算
342+465 = 807的過程葱色。
這題最好的解法是programcreek里提供的拒名,利用while()里面的||循環(huán)刽严,非常簡潔易懂。相比之下code ganker還有其他一些人的解法就繁瑣多了溉旋,他們的while循環(huán)是用&&的救军,導(dǎo)致需要分別處理l1和l2!=null的情況,非常復(fù)雜毒嫡。以后還是多看幾種解法比較好癌蚁。
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里的兜畸∨停可以看看。