Add Two Numbers II

题目:

You have two numbers represented by a linked list, where each node contains a single digit. The digits are stored in forward order, such that the 1's digit is at the head of the list. Write a function that adds the two numbers and returns the sum as a linked list.

分析:

总是写着写着就忘记了最后要reverse一次再返回值。

解法:

class Solution {
public:
    /**
     * @param l1: the first list
     * @param l2: the second list
     * @return: the sum list of l1 and l2 
     */

    ListNode* reverseList(ListNode* head) {
        if (head == NULL || head->next == NULL) {
            return head;
        }
        ListNode dummy(0);
        dummy.next = head;

        ListNode* curr = head;
        while (curr->next != NULL) {
            ListNode* next = curr->next;
            curr->next = next->next;
            next->next = dummy.next;
            dummy.next = next;
        }

        return dummy.next;
    }

    ListNode *addLists2(ListNode *l1, ListNode *l2) {
        // write your code here
        if (l1 == NULL) {
            return l2;
        }
        if (l2 == NULL) {
            return l1;
        }

        l1 = reverseList(l1);
        l2 = reverseList(l2);

        ListNode dummy(0);
        ListNode* curr = &dummy;
        int carry = 0;

        while (l1 != NULL && l2 != NULL) {
            curr->next = new ListNode( (l1->val + l2->val + carry) % 10 );
            carry = (l1->val + l2->val + carry) / 10;

            curr = curr->next;
            l1 = l1->next;
            l2 = l2->next;
        }

        while (l1 != NULL) {
            curr->next = new ListNode( (l1->val + carry) % 10 );
            carry = (l1->val + carry) / 10;

            curr = curr->next;
            l1 = l1->next;
        }

        while (l2 != NULL) {
            curr->next = new ListNode( (l2->val + carry) % 10 );
            carry = (l2->val + carry) / 10;

            curr = curr->next;
            l2 = l2->next;
        }

        if (carry != 0) {
            curr->next = new ListNode(carry);
            carry /= 10;
        }

        return reverseList(dummy.next);
    }
};

results matching ""

    No results matching ""