您的位置:首页 > 其它

leetcode 002 Add_Two_Numbers

2017-05-08 23:46 295 查看
/**
* 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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: