[leetcode]Add Two Numbers

- -简单题

处理好进位,还有两个链表不一样长就好

/**
 * 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) {
        // Note: The Solution object is instantiated only once and is reused by each test case.
        if (l1 == NULL) return l2;
        if (l2 == NULL) return l1;

        int val = (l1 -> val + l2 -> val) % 10 ;
        int mod = (l1 -> val + l2 -> val) / 10;
        
        ListNode* head = new ListNode(val);
        ListNode* tmp = head;
        l1 = l1 -> next ; l2 = l2 -> next;
        
        while(l1 != NULL && l2 != NULL){
            val = (l1 -> val + l2 -> val + mod) % 10;
            mod = (l1 -> val + l2 -> val + mod) / 10;
            
            ListNode* newN = new ListNode(val);
            tmp -> next = newN;
            tmp = newN;
            l1 = l1 -> next ; l2 = l2 -> next;
        }
        if(l1 != NULL){
    
            while(l1 != NULL)     
            {
                val = (l1 -> val + mod) % 10;
                mod = (l1 -> val + mod) / 10;
            
                ListNode* newN = new ListNode(val);
                tmp -> next = newN;
                tmp = newN;
                l1 = l1 -> next;
            }
        }
        if(l2 != NULL){
            while(l2 != NULL)     
            {
                val = (l2 -> val + mod) % 10;
                mod = (l2 -> val + mod) / 10;
            
                ListNode* newN = new ListNode(val);
                tmp -> next = newN;
                tmp = newN;
                l2 = l2 -> next;
            }
            
        }
        if(mod > 0){
            ListNode* newN = new ListNode(mod);
            tmp -> next = newN;
        }
        return head;
    }
};

  

你可能感兴趣的:(LeetCode)