Description
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.
Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
Explanation: 342 + 465 = 807.
Solution
簡單的鏈表加法,說實話,定義成medium有點牽強。注意進位信息,while的判定條件很妙。在做鏈表題的時候,經常會遇到首節點不方便處理,注意虛擬節點dummy的用法,能省去不少邊界條件的判定。
時間O(m+n),空間O(m+n),能夠AC,沒有考慮去復用l1或者l2的空間
ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
auto dummy = new ListNode(-1), pNode = dummy;
int carry = 0;
while (l1 || l2 || carry) {
int sum = (l1?l1->val:0) + (l2?l2->val:0) + carry;
pNode->next = new ListNode(sum%10);
carry = sum/10;
pNode = pNode->next;
l1 = (l1?l1->next:NULL);
l2 = (l2?l2->next:NULL);
}
return dummy->next;
}