【Leetcode】Add Two Numbers

问题:

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

代码:

//
//  ad2num.cpp
//  Test
//
//  Created by mac on 5/19/14.
//  Copyright (c) 2014 mac. All rights reserved.
//

#include "ad2num.h"
#include <iostream>

using namespace std;

 struct ListNode {
     int val;
     ListNode *next;
     ListNode(int x) : val(x), next(NULL) {}
};

class Solution {
public:
    ListNode *addTwoNumbers(ListNode *l1, ListNode *l2) {
        ListNode *returnL = NULL;
        ListNode *haha = returnL;
        int tenth = 0;
        while(l1 && l2)
        {
            int temp = l1->val + l2->val + tenth;
            tenth = temp/10;
            int num = temp%10;
            if(!returnL)
            {
                returnL = new ListNode(num);
                haha = returnL;
            }
            else
            {
                haha->next = new ListNode(num);
                haha = haha->next;
            }
            l1 = l1->next;
            l2 = l2->next;
        }
        
        ListNode *lastList = l1?l1:l2;
        
        while(lastList)
        {
            int temp =  lastList->val + tenth;
            tenth = temp/10;
            int num = temp%10;
            
            if(!returnL)
            {
                returnL = new ListNode(num);
                haha = returnL;
            }
            else
            {
                haha->next= new ListNode(num);
                haha = haha->next;
            }
            lastList = lastList->next;
        }
        
        if(returnL && tenth)
        {
            haha->next= new ListNode(tenth);
            haha = haha->next;
        }
        
        return returnL;
    }
};

int main()
{
    ListNode *l1 = new ListNode(1);
    //l1->next = new ListNode(4);
    //l1->next->next = new ListNode(3);
    
    ListNode *l2 = new ListNode(9);
    l2->next = new ListNode(9);
    l2->next->next = new ListNode(9);
    
    Solution s;
    
    ListNode *result =s.addTwoNumbers(l1 , l2);
    while(result)
    {
        cout<<result->val<<endl;
        result = result->next;
    }

}

分析:

主要考的内容是链表的掌握。有三个需要注意:

1.链表有可能都是空的,或者某一个为空。

2. 加法有进位,尽管把其中一个链表加到空了,依然得注意到进位,比如 1 + 999 ,显然虽然前面那个队列很快就空了,可留下来的进位不能够丢弃。

3. 最后剩下的链表也不能够简单的链接到新的链表后面,理由和2一样,1+999这种情况,显然把进位带到了最后。


总结:

这个很简单,一次性编译,就成功了,没调试就算对了,通过了网上的检验,数据结构链表部分掌握的还不错。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值