首页 > 其他 > 详细

Leetcode Add Two Numbers

时间:2014-06-07 03:44:00      阅读:362      评论:0      收藏:0      [点我收藏+]
bubuko.com,布布扣
class Solution {
public:
    ListNode *addTwoNumbers(ListNode *l1, ListNode *l2) {
        ListNode* p = l1;
        ListNode* q = l2;
        ListNode* ret = NULL;
        ListNode* ret_cur = NULL;
        int carry = 0;
        int digit = 0;
        while (p != NULL && q != NULL) {
            carry = add_node(p->val + q->val + carry, ret, ret_cur);
            p = p->next;
            q = q->next;
        }
        while (p != NULL) {
            carry = add_node(p->val + carry, ret, ret_cur); 
            p = p->next;
        }
        while (q != NULL) {
            carry = add_node(q->val + carry, ret, ret_cur); 
            q = q->next;
        }
        if (carry) add_node(1, ret, ret_cur);
        return ret;
    }   

    int add_node(int val, ListNode* &head, ListNode* &cur) {
        int carry = val / 10; 
        int digit = carry == 0 ? val : val - 10; 
        ListNode* cur_res = new ListNode(digit);
        if (head == NULL) {
            head = cur_res;
            cur = cur_res;
        } else {
            cur->next = cur_res;
            cur = cur_res;
        }
        return carry;
    }   
};
bubuko.com,布布扣

水一发

Leetcode Add Two Numbers,布布扣,bubuko.com

Leetcode Add Two Numbers

原文:http://www.cnblogs.com/lailailai/p/3756055.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!