凌云的博客

成功=工作+游戏+少说空话

LeetCode 算法题 2. Add Two Numbers

分类:algorithm| 发布时间:2016-06-23 22:42:00


题目

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

思路

给出两个代表非负整数的链表。 链表中的数字是以反序保存的,并且每个节点包含一个单独的数字。 以链表形式返回这两个数字相加的结果。

创建一个新的链表来保存结果,从头到尾遍历给出的链表 , 将每个链表对应节点相加的结果保存为新的节点,并插入到结果链表的尾部。 需要注意处理进位以及两个列表长度不同的情况。

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) {
        ListNode *ret = new ListNode(0);
        ListNode *p = ret, *tmp, *prev = p;
        int carry = 0, tmpVal;

        while (l1 && l2) {
            tmpVal = carry + l1->val + l2->val;
            if (tmpVal >= 10) {
                carry = 1;
                tmpVal -= 10;
            } else {
                carry = 0;
            }

            p->val = tmpVal;
            tmp = new ListNode(tmpVal);
            prev = p;
            p->next = tmp;
            p = tmp;
            l1 = l1->next;
            l2 = l2->next;
        }

        while (l1) {
            tmpVal = carry + l1->val;
            if (tmpVal >= 10) {
                carry = 1;
                tmpVal -= 10;
            } else {
                carry = 0;
            }

            p->val = tmpVal;
            tmp = new ListNode(0);
            prev = p;
            p->next = tmp;
            p = tmp;
            l1 = l1->next;
        }

        while (l2) {
            tmpVal = carry + l2->val;
            if (tmpVal >= 10) {
                carry = 1;
                tmpVal -= 10;
            } else {
                carry = 0;
            } 

            p->val = tmpVal;
            tmp = new ListNode(0);
            prev = p;
            p->next = tmp;
            p = tmp;
            l2 = l2->next;
        }

        if (carry) {
            p->val = carry;
        } else {
            if (p == ret) {
                delete p;
                ret = NULL;
            } else {
                prev->next = NULL;
                delete p;
            }
        }

        return ret;
    }
};