LeetCode - 链表求和

低位在前

https://leetcode.cn/problems/sum-lists-lcci/

    void handleRestBits(ListNode* cur, int extraOne)
    {
        while(extraOne)
        {
            int add = cur->val + extraOne;
            extraOne = add / 10;
            cur->val = add % 10;
            if (extraOne && cur->next == nullptr)
            {
                cur->next = new ListNode{1};
                break;
            }
            cur = cur->next;
        }        
    }

    ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
        if (l1 == nullptr) return l2;
        if (l2 == nullptr) return l1;

        int extraOne = 0;
        ListNode* cur1 = l1;
        ListNode* cur2 = l2;
        ListNode* pre = NULL;
        while(cur1 && cur2)
        {
            int add = cur1->val + cur2->val + extraOne;
            extraOne = add / 10;
            cur1->val = cur2->val = add % 10;
            pre = cur1;
            cur1 = cur1->next;
            cur2 = cur2->next;
        }

        if (cur1)
        {
            handleRestBits(cur1, extraOne);
            return l1;
        }
        else if (cur2)
        {
            handleRestBits(cur2, extraOne);
            return l2;
        }
        else
        {
            if (extraOne)
            {
                pre->next = new ListNode{1};
            }
            return l1;
        }
    }

你可能感兴趣的:(leetcode,leetcode,链表,算法)