An ordinary C++ solution.


  • 0
    T
    /**
     * 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) {
            //If either one is a nullptr, then simply return the other.
            if (l1 == nullptr) {
                return l2;
            } else if (l2 == nullptr) {
                return l1;
            }
            
            //The first node in the linked list.
            ListNode* headNode = nullptr;
            //The node at the end of the linked list.
            ListNode* rearNode = nullptr;
            
            //The carry of the addition.
            int carry = 0;
            do {
                int result = carry;
                
                if (l1 != nullptr) {
                    result += l1->val;
                    l1 = l1->next;
                }
                if (l2 != nullptr) {
                    result += l2->val;
                    l2 = l2->next;
                }
                
                carry = result / 10;
                result %= 10;
                
                //Store the result into the node for the current loop.
                ListNode* newNode = new ListNode(result);
                if (headNode == nullptr) {
                    headNode = newNode;
                    rearNode = newNode;
                } else {
                    rearNode->next = newNode;
                    rearNode = rearNode->next;
                }
            } while (l1 != nullptr || l2 != nullptr || carry != 0);
            
            return headNode;
        }
    };
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.