码迷,mamicode.com
首页 > 其他好文 > 详细

Leetcode Add Two Numbers

时间:2014-06-07 03:50:49      阅读:218      评论:0      收藏:0      [点我收藏+]

标签:c   style   class   blog   code   java   

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

标签:c   style   class   blog   code   java   

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!