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

【leetcode】2. Add Two Numbers

时间:2015-07-15 17:09:17      阅读:179      评论:0      收藏:0      [点我收藏+]

标签:leetcode   链表相加   

@requires_authorization
@author johnsondu
@create_time 2015.7.15 14:54
@url [add two numbers](https://leetcode.com/problems/add-two-numbers/)
/**
 *    链表模拟大数相加
 *    时间复杂度: O(n)
 *    空间复杂度: O(n)
 */
/**
 * 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 *head = new ListNode(0);
        ListNode *cur = head;

        int carry = 0;
        while(l1 || l2 || carry){
            int tmp = carry;
            if(l1 != NULL) {
                tmp = tmp + l1->val;
                l1 = l1->next;
            }
            if(l2 != NULL) {
                tmp = tmp + l2->val;
                l2 = l2->next;
            }
            carry = tmp / 10;
            ListNode *node = new ListNode(tmp % 10);
            cur->next = node;
            cur = cur->next;
        }
        return head->next;
    }
};

版权声明:本文为博主原创文章,未经博主允许不得转载。

【leetcode】2. Add Two Numbers

标签:leetcode   链表相加   

原文地址:http://blog.csdn.net/zone_programming/article/details/46893543

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