[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

 

这题虽然归类到Medium 但是难度不大,只是要考虑的东西有点多,比如:两个list不一定一样长,进位这两个问题。

因为两个数字是逆序存到链表里的,所以这大大简化了问题难度,因为只需要向着链表遍历方向往前进位就可以了。

void addIter(ListNode *l1, ListNode *l2, ListNode *prev, int carry) {
    if (!l1 && !l2 && carry == 0) return;
    ListNode *node;
    int val = 0;
    if (l1) {
        val += l1->val;
    }
    if (l2) {
        val += l2->val;
    }
    val += carry;
    carry = val / 10;
    val = val % 10;
    
    node = new ListNode(val);
    if (prev) {
        prev->next = node;
    }
    
    addIter(l1 ? l1->next : NULL, l2 ? l2->next : NULL, node, carry);
}

ListNode *addTwoNumbers(ListNode *l1, ListNode *l2) {
    ListNode *ret = new ListNode(0);
    addIter(l1, l2, ret, 0);
    return ret->next;
}

 

posted @ 2014-11-24 08:51  Agentgamer  阅读(123)  评论(0编辑  收藏  举报