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

LeetCode "445. Add Two Numbers II"

时间:2017-01-27 07:21:27      阅读:246      评论:0      收藏:0      [点我收藏+]

标签:nat   null   empty   close   ptr   nod   ima   ack   image   

A natural stack based solution. Seriously, whey ‘Medium‘?

技术分享
/**
 * 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) {
        stack<ListNode*> s1, s2;
        ListNode *p = l1;
        while(l1)
        {
            s1.push(l1); l1 = l1->next;
        }
        p = l2;
        while(l2)
        {
            s2.push(l2); l2 = l2->next;
        }
        
        //
        ListNode *pc = nullptr, *pp = nullptr;
        int carry = 0;
        while(!s1.empty() || !s2.empty())
        {
            int a1 = 0;
            if(!s1.empty())
            {
                a1 = s1.top()->val;
                s1.pop();
            }
            
            int a2 = 0;
            if(!s2.empty())
            {
                a2 = s2.top()->val;
                s2.pop();
            }
            
            int sum = (a1 + a2 + carry) % 10;
            carry = (a1 + a2 + carry) / 10;
            
            pp = new ListNode(sum);
            pp -> next = pc;
            pc = pp;
        }
        if(carry)
        {
            pp = new ListNode(carry);
            pp -> next = pc;
        }
        
        return pp;
    }
};
View Code

 

LeetCode "445. Add Two Numbers II"

标签:nat   null   empty   close   ptr   nod   ima   ack   image   

原文地址:http://www.cnblogs.com/tonix/p/6353616.html

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