leetcode 002 Add_Two_Numbers


/**
* You are given two non-empty linked lists representing two non-negative integers. 
* 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.
* You may assume the two numbers do not contain any leading zero, except the number 0 itself.

* Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
* Output: 7 -> 0 -> 8

*/

/********************************/

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}          //构造函数初始化
 * };
 */

//by ln 2017-5-08

#include <iostream>
#include <string>
#include <algorithm>
#include <cmath>

using namespace std;

//数据结构
struct ListNode{
    int val;
    ListNode *next;
    ListNode(int x):val(x),next(NULL){}
};


//尾插法

ListNode *addValAndCreateNewNode(ListNode *cur,int val){
    cur->val=val;
    cur->next=new ListNode(0);
    return cur->next;
}

//生产一个倒叙的列表
ListNode *parseInput(int n){
    int t;
    ListNode *a = new ListNode(0);
    ListNode *pa=a;

    while(n--){

        cout<<"input the single number :";
        cin>>t;

        pa=addValAndCreateNewNode(pa,t); //生成链表
    }

    return a;
}

class Solution {  
public:  
    ListNode *addTwoNumbers(ListNode *l1, ListNode *l2) {  


        ListNode* c1 = l1;  
        ListNode* c2 = l2;  
        ListNode* d = new ListNode(0);          
        ListNode* head = d;  
        int carry = 0;  

        while(c1 != NULL || c2 != NULL)  
        {  
            int sum = 0;  
            if(c1 != NULL)  
            {  
                sum += c1->val;  
                c1 = c1->next;  
            }  
            if(c2 != NULL)  
            {  
                sum += c2->val;  
                c2 = c2->next;  
            }  
            int tmp = sum + carry;  
            d->next = new ListNode(tmp % 10);       
            d = d->next;                            
            carry = tmp / 10;  
        }  


        if(carry != 0)  
            d->next = new ListNode(carry);  

        return head->next;  
    }  
};



int main()
{
    //输入个数,n1代表第一个链表位数,n2代表第二个链表的位数
    int n1,n2;
    Solution s;

    cout<<"please input the number of list A: ";
    cin>>n1;

    ListNode *a = parseInput(n1);

    cout<<"please input the number of list B: ";
    cin>>n2;
    ListNode *b = parseInput(n2);

    ListNode* result=s.addTwoNumbers(a,b); //a,b not release!

    while (result->next != NULL)
    {
        cout<<result->val;
        result= result->next;
    }
    cout<<endl;
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值