LeetCode Add Two Numbers C++

#include <iostream>
#include <vector>
#include<algorithm>
#include <queue>
using namespace std;

/************************************************************************/
/* 
    Problem:
        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
   //其实就是   342+465 = 807 
    Author  :   crazys_popcorn@126.com

    DateTime:   2017年8月7日 17:41:33

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





struct ListNode {
    int val;
    ListNode *next;
    ListNode(int x) : val(x), next(NULL) {}
};
class Solution {
public:
    ListNode* addTwoNumbers(ListNode* l1, ListNode* l2)
    {
        //双指针。指向同一个开始位置。用于返回
        ListNode *List = new ListNode(0);
        ListNode *head = List;   
        int jinwei = 0;
        if (l1 == NULL && l2 == NULL)
            return NULL;

        while (l1||l2)
        {
            //把给个位数相加。     //第一轮进位为0.第二轮看看上一轮的进位是否大于10 大于10 就是1
            int num =( l1 ? l1->val:0 )+ (l2 ? l2->val:0) + jinwei;
            if (num >= 10)
            {
                num -= 10;
                //大于10 进位 1   
                jinwei = 1;
            }
            else
                jinwei = 0;
            //当前为不修改。直接修改 next 一个元素。
            List->next = new ListNode(num);
            //把指针,移到下一位  //重复上面步骤。 修改下一位。  
            List = List->next; 
            if (l1)
                l1 = l1->next;
            if (l2)
                l2 = l2->next;
        }
        if (jinwei)
        {
            //看看最后的哪一位。是不是进位了。
            List->next = new ListNode(1);
        }
        return head->next;

    }
};

void main()
{

    ListNode *t1 = new ListNode(0);
    ListNode *t2 = new ListNode(0);
    ListNode *t3 = new ListNode(0);
    t1->val = 2;
    t2->val = 4;
    t3->val = 3;
    t1->next = t2;
    t2->next = t3;
    ListNode *t11 = new ListNode(0);
    ListNode *t22 = new ListNode(0);
    ListNode *t33 = new ListNode(0);
    t11->val = 5;
    t22->val = 6;
    t33->val = 4;
    t11->next = t22;
    t22->next = t33;
    Solution s1;
    s1.addTwoNumbers(t1, t11);
    system("pause");
    return ;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值