https://leetcode-cn.com/problems/add-two-numbers/description/
給定兩個非空鏈表來表示兩個非負(fù)整數(shù)蹂安。位數(shù)按照逆序方式存儲柳譬,它們的每個節(jié)點只存儲單個數(shù)字完箩。將兩數(shù)相加返回一個新的鏈表粥诫。
你可以假設(shè)除了數(shù)字 0 之外十绑,這兩個數(shù)字都不會以零開頭漱挎。
示例
輸入:(2 -> 4 -> 3) + (5 -> 6 -> 4)
輸出:7 -> 0 -> 8
原因:342 + 465 = 807
主要思路:
思路很直接廉涕,直接采用雙指針來實現(xiàn),需要考慮進(jìn)位的情況曙砂。
/**
* 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) {
int bonus = 0;
ListNode* head = new(std::nothrow) ListNode(0);
ListNode* curr = head;
ListNode* next1 = l1;
ListNode* next2 = l2;
while (next1 != NULL || next2 != NULL) {
int val1 = 0;
if (next1 != NULL) {
val1 = next1->val;
next1 = next1->next;
}
int val2 = 0;
if (next2 != NULL) {
val2 = next2->val;
next2 = next2->next;
}
int val = (val1 + val2 + bonus);
ListNode* node = new(std::nothrow) ListNode(val % 10);
curr->next = node;
curr = node;
bonus = val / 10;
}
if (bonus != 0) {
ListNode* node = new(std::nothrow) ListNode(bonus);
curr->next = node;
}
return head->next;
}
};