Easy to understand O(n) C++ solution using vector


  • 2
    Q
    class Solution {
        vector<int> convertToVector(ListNode *head) {
            vector<int> res;
            while (head) {
                res.push_back(head->val);
                head = head->next;
            }
            return res;
        }
        ListNode* addTwoVector(vector<int> v1, vector<int> v2) {
            ListNode *dummy = new ListNode(0), *node = NULL;
            int i = v1.size() - 1, j = v2.size() - 1, sum = 0;
            while (j >= 0 || i >= 0 || sum) {
                if (i >= 0) sum += v1[i--];
                if (j >= 0) sum += v2[j--];
                node = new ListNode(sum % 10);
                sum /= 10;
                node->next = dummy->next;
                dummy->next = node;
            }
            return dummy->next;
        }
    public:
        ListNode* addTwoNumbers(ListNode *l1, ListNode *l2) {
            return addTwoVector(convertToVector(l1), convertToVector(l2));
        }
    };
    

  • 0
    Y

    very good solution to this problem, I wrote the code with the same meaning but with too many lines, very useful for me! thank you~


Log in to reply
 

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