題目描述:
給出兩個 非空 的鏈表用來表示兩個非負的整數。其中,它們各自的位數是按照 逆序 的方式存儲的,並且它們的每個節點只能存儲 一位 數字。
如果,我們將這兩個數相加起來,則會返回一個新的鏈表來表示它們的和。
您可以假設除了數字 0 之外,這兩個數都不會以 0 開頭。
示例:
輸入:(2 -> 4 -> 3) + (5 -> 6 -> 4) 輸出:7 -> 0 -> 8 原因:342 + 465 = 807
思路:
1.相加的過程中可能存在進位的操作,所以需要采用一個變量carry來記錄進位的情況,初始化carry = 0;
2.因為鏈表的數字是倒着放的,所以相加起來很方便,將兩個鏈表從頭到尾一起遍歷,如果有值的話就將它們的值相加sum = val1+val2+carry。
3.如果是兩個長度不一樣的鏈表,則需要注意將不再繼續向后,且讓相應位的和為val1+0.
4.carry的更新,carry = sum/10, 而當前節點和 curr->val = sum%10.
5.循環直至l1,l2都為空。
6.遍歷完之后如果carry == 1, 新建一個節點存在進位。
實現代碼:
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */ class Solution { public: ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) { ListNode *newHead = new ListNode(0); ListNode *p = l1; ListNode *q = l2; ListNode *curr = newHead; int carry = 0; while(p != NULL || q != NULL){ int sum = 0, x = 0, y = 0; if(p){ x = p->val; p = p->next; } if(q){ y = q->val; q = q->next; } sum = x + y + carry; carry = sum/10; curr->next = new ListNode(sum % 10); curr = curr->next; } if(carry) { curr->next = new ListNode(carry); } return newHead->next; } };