[LeetCode] 2. Add Two Numbers

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

You may assume the two numbers do not contain any leading zero, except the number 0 itself.

Example:

Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
Explanation: 342 + 465 = 807.

用加法合并两个单链表

开始我想把l2合并到l1去,发现我搞不定,于是把l1 l2合并到一个新的链表中去,下面是第一个版本

ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
    if (! (l1 && l2))
    {
        return l1 ? l2: l1;
    }

    int carry = 0;

    ListNode* root = new ListNode(l1->val + l2->val);
    carry = root->val / 10;
    root->val %= 10;

    ListNode* l3 = root;

    l1 = l1->next;
    l2 = l2->next;

    while (l1 || l2)
    {
        int v1 = l1 ? l1->val : 0;
        int v2 = l2 ? l2->val : 0;

        ListNode* tmp = new ListNode(v1 + v2 + carry);
        carry = tmp->val / 10;
        tmp->val %= 10;
        root->next = tmp;
        root = root->next;

        l1 = l1 ? l1->next : NULL;
        l2 = l2 ? l2->next : NULL;
    }

    if (carry != 0) //l1 l2都没了,但有进位,需加一个ListNode
    {
        ListNode * tmp = new ListNode(1);
        root->next = tmp;
    }

    return l3;
}

我看了LeetCode上最好的那份代码,比我的好多了,于是新的代码如下(copy & paste)

ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
    int carry = 0;
    ListNode *root = nullptr, *l3 = nullptr;

    while (l1 || l2 || carry)
    {
        if (l1)
        {
            carry += l1->val;
            l1 = l1->next;
        }

        if (l2)
        {
            carry += l2->val;
            l2 = l2->next;
        }

        if (l3)
        {
            l3->next = new ListNode(carry % 10);
            l3 = l3->next;
        }
        else
        {
            root = new ListNode(carry % 10);
            l3 = root;
        }

        carry /= 10;
    }

    return root;
}
posted @ 2018-08-20 10:52  arcsinW  阅读(133)  评论(0编辑  收藏  举报