給你兩個 非空 鏈表來代表兩個非負整數。數字最高位位於鏈表開始位置。它們的每個節點只存儲一位數字。將這兩數相加會返回一個新的鏈表。
你可以假設除了數字 0 之外,這兩個數字都不會以零開頭。
進階:
如果輸入鏈表不能修改該如何處理?換句話說,你不能對列表中的節點進行翻轉。
示例:
輸入:(7 -> 2 -> 4 -> 3) + (5 -> 6 -> 4)
輸出:7 -> 8 -> 0 -> 7
如果不能對列表中的節點進行翻轉,則必須要使用輔助內存。因爲鏈表是倒序的,所以可以使用棧來比較容易地將字符串反序。
/*
法二:棧
本題的主要難點在於鏈表中數位的順序與我們做加法的順序是相反的,爲了逆序處理所有數位,我們
可以使用棧:把所有數字壓入棧中,再依次取出相加。計算過程中需要注意進位的情況。
*/
class Solution {
public:
ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
stack<int> s1, s2;
while (l1) {
s1.push(l1->val);
l1 = l1->next;
}
while (l2) {
s2.push(l2->val);
l2 = l2->next;
}
int carry = 0;
ListNode* ans = NULL;
while (!s1.empty() || !s2.empty() || carry != 0) {
int a = s1.empty() ? 0 : s1.top();
int b = s2.empty() ? 0 : s2.top();
if (!s1.empty()) s1.pop();
if (!s2.empty()) s2.pop();
int cur = a + b + carry;
carry = cur / 10;
cur %= 10;
auto curnode = new ListNode(cur);
curnode->next = ans;
ans = curnode;
}
return ans;
}
};