002 Add Two Numbers [Leetcode]

来源:互联网 发布:纠正英语发音的软件 编辑:程序博客网 时间:2024/05/17 06:22

题目内容:

You are given two linked lists representing two non-negative numbers. 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.

Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8

解题思路:
没什么技巧,注意进位即可(包括每一位进位与最高位进位)。

class Solution {public:    ListNode *addTwoNumbers(ListNode *l1, ListNode *l2) {        if(l1 == NULL && l2 == NULL)            return NULL;        else if(l1 == NULL)            return l2;        else if(l2 == NULL)            return l1;        bool carry = false;        ListNode *head = new ListNode(0), *curr = head;        while(l1 != NULL && l2 != NULL) {            curr->next = addDigit(l1->val, l2->val, carry);            curr = curr->next;            l1 = l1->next;            l2 = l2->next;        }        if(l1 == NULL)            l1 = l2;        while(carry && l1 != NULL) {            curr->next = addDigit(l1->val, 0, carry);            curr = curr->next;            l1 = l1->next;        }        if(carry)            curr->next = new ListNode(1);        copyList(curr, l1);        curr = head;        head = head->next;        delete curr;        return head;    }    void copyList(ListNode *l1, ListNode *l2) {        while(l2 != NULL) {            l1->next = new ListNode(l2->val);            l1 = l1->next;            l2 = l2->next;        }    }    ListNode *addDigit(int val1, int val2, bool &carry) {        int val(val1 + val2);        if(carry) {            ++val;            carry = false;        }        if(val >= 10) {            val -= 10;            carry = true;        }        return new ListNode(val);    }};
0 0
原创粉丝点击