Leetcode#2 Add Two Numbers

less than 1 minute read

Published:

https://leetcode.com/problems/add-two-numbers/description/

Idea:

Linklist traverse, be careful about loop end condition.

Solution:

/**
 * 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 (l1 == NULL && l2 == NULL)
                return NULL;
            if (l1 == NULL)
                return l2;
            if (l2 == NULL)
                return l1;

            ListNode* res = new ListNode(0);
            ListNode* head = res;
            ListNode* prev = NULL;
            int carry = 0;
            while ( l1 || l2 || carry ) {
                if (l1) {
                    res->val += l1 -> val;
                    l1 = l1->next;
                }
                if (l2) {
                    res->val += l2->val;
                    l2 = l2->next;
                }
                if (res->val >= 10) {
                    res->val -= 10;
                    carry = 1;
                }else {
                    carry = 0;
                }
                res->next = new ListNode(carry);
                prev = res;
                res = res->next;
            }
            if (prev)
                prev->next = NULL;
            return head;
        }
};