程序员面试金典 2.5

Sum Lists：将两个单链表所表示的十进制数求和，数位是逆序的，也就是个位是第一个节点。如果个位最后一个节点又该如何做呢？

/**
* struct ListNode {
*     int val;
*     ListNode *next;
*     ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
int carry = 0;
while(l1 != nullptr && l2 != nullptr){
*curr = new ListNode(l1->val + l2->val + carry);
carry = (*curr)->val / 10;
(*curr)->val %= 10;
curr = &(*curr)->next;
l1 = l1->next;
l2 = l2->next;
}
while(l1 != nullptr){
*curr = new ListNode(l1->val + carry);
carry = (*curr)->val / 10;
(*curr)->val %= 10;
curr = &(*curr)->next;
l1 = l1->next;
}
while(l2 != nullptr){
*curr = new ListNode(l2->val + carry);
carry = (*curr)->val / 10;
(*curr)->val %= 10;
curr = &(*curr)->next;
l2 = l2->next;
}
if(carry != 0){
*curr = new ListNode(carry);
}
}
};


/**
* struct ListNode {
*     int val;
*     ListNode *next;
*     ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
}
private:
ListNode* doAddTwoNumbers(ListNode* l1, ListNode* l2, int carry)
{
if(l1 == nullptr && l2 == nullptr && carry == 0){
return nullptr;
}
ListNode* res = new ListNode(carry);
if(l1 != nullptr){
res->val += l1->val;
}
if(l2 != nullptr){
res->val += l2->val;
}
carry = res->val / 10;
res->val %= 10;
res->next = doAddTwoNumbers(l1 ? l1->next : nullptr,
l2 ? l2->next : nullptr,
carry);
return res;
}
};


©️2019 CSDN 皮肤主题: 大白 设计师: CSDN官方博客