LeetCode题解:Add Two Numbers

题目:
You are given two linked lists representing two non-negative numbers. 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.

Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8

/**
 * 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* sum = 0;
        ListNode* head = 0;
        int carry = 0;
        while (l1 && l2) {
            int val = l1->val + l2->val + carry;
            if (val >= 10) {
                carry = val/10;
                val %= 10;
            } else {
                carry = 0;
            }
            ListNode* node = new ListNode(val);
            if (head == 0) {
                head = node;
                sum = node;
            } else {
                sum->next = node;
                sum = sum->next;
            }
            l1 = l1->next;
            l2 = l2->next;
        }
        while (l1) {
            int val = l1->val + carry;
            if (val >= 10) {
                val %= 10;
            } else {
                carry = 0;
            }
            ListNode* node = new ListNode(val);
            sum->next = node;
            sum = sum->next;
            l1 = l1->next;
        }
        while (l2) {
            int val = l2->val + carry;
            if (val >= 10) {
                val %= 10;
            } else {
                carry = 0;
            }
            ListNode* node = new ListNode(val);
            node->next = 0;
            sum->next = node;
            sum = sum->next; 
            l2 = l2->next;
        }
        if (carry > 0) {
            ListNode* node = new ListNode(carry);
            node->next = 0;
            sum->next = node;
            sum = sum->next;
        }
        return head;
    }
};

显然,空间复杂度:O(n),时间复杂度O(n)

你可能感兴趣的:(LeetCode题解:Add Two Numbers)