--

leetcode 002: add two numbers



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



problem:
  
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.


start code (c++)
/**
 * 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) {
        
    }
};




solution 1:
/**
 * 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) {
        ListNode* l3 = NULL;
        int carry = 0;
        while (l1 || l2 || carry){
            int d1 = l1 ? l1->val : 0;
            int d2 = l2 ? l2->val : 0;
            int d3 = d1 + d2 + carry;
            if (d3 >= 10){
                d3 -= 10;
                carry = 1;
            }else{
                carry = 0;
            }
            
            ListNode* temp = new ListNode(d3);
            temp->next = l3;
            l3 = temp;
            if (l1)
                l1 = l1->next;
            if (l2)
                l2 = l2->next;
        }
        
        # reverse l3
        ListNode *l4 = NULL;
        while (l3){
            ListNode* temp = l3;
            l3 = l3->next;
            temp->next = l4;
            l4 = temp;
        }
        return l4;
    }
};

solution 2:



/**
 * 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) {
        ListNode* head = NULL;
        ListNode* tail = head;
        int carry = 0;
        while (l1 || l2 || carry){
            int d1 = l1 ? l1->val : 0;
            int d2 = l2 ? l2->val : 0;
            int d3 = d1 + d2 + carry;
            if (d3 >= 10){
                d3 -= 10;
                carry = 1;
            }else{
                carry = 0;
            }
            
            ListNode* l3 = new ListNode(d3);
            if (tail == NULL){
                head = l3;
                tail = l3;
            }else{
                tail->next = l3;
                tail = l3;
            }
            if (l1)
                l1 = l1->next;
            if (l2)
                l2 = l2->next;
        }
        return head;
    }
};