LeetCode_2-Add_Two_Numbers

本文介绍了一种链表求和的算法实现,该算法接受两个非空链表作为输入,这两个链表分别代表两个非负整数。数字以逆序方式存储在链表中,每个节点包含一个单独的数字。通过此算法可以将两个数字相加并以链表形式返回结果。

本人博客已经迁移到nasdaqgodzilla.github.io


#include <iostream>

/*
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)    -->  342 + 465
Output: 7 -> 0 -> 8         --> result == 807
*/

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */

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

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

using namespace std;

//题目没有明确说明两个list的长度相等
ListNode* Solution::addTwoNumbers(ListNode* l1,ListNode* l2)
{
    if(NULL == l1 || NULL == l2){
        return nullptr;
    }

    bool carry = false;             //进位标志
    auto left = l1,right = l2;
    auto ret = new ListNode(0);
    auto ret_head = ret;            //记录第一个节点,即为list头

    do{
        ret->val = left->val + right->val;
        if(carry){
            ret->val += 1;          //进位标志只提供一进位而没有更多进位,因为题目要求并不会出现相加后大于二十,因此进位最多为1
            carry = false;
        }
        if(ret->val >= 10){
            ret->val -= 10;
            carry = true;
        }
        left = left->next;
        right = right->next;
        ret->next = new ListNode(-1);   //构造下一节点
        ret = ret->next;                //让当前节点指向下一节点
    }while(left != nullptr && right != nullptr);

    return ret_head;                    //返回list的头结点
}

int main()
{   /*注意:题目要求list中每一个node的值都是一个digital,即每个节点出现的数值为[-9,-9]*/
    ListNode* x1 = new ListNode(2);
    ListNode* x2 = new ListNode(4);
    ListNode* x3 = new ListNode(3);
    x1->next = x2;
    x2->next = x3;
    x3->next = nullptr;

    ListNode* y1 = new ListNode(5);
    ListNode* y2 = new ListNode(6);
    ListNode* y3 = new ListNode(4);
    y1->next = y2;
    y2->next = y3;
    y3->next = nullptr;

    auto ret = Solution::addTwoNumbers(x1,y1);
    for(;ret != nullptr && ret->val > -1;ret = ret->next){
        cout << ret->val << "-";
    }
    cout<<endl;

    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值