力扣 2.两数相加 c/c++

在这里插入图片描述

C

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     struct ListNode *next;
 * };
 */
struct ListNode* addTwoNumbers(struct ListNode* l1, struct ListNode* l2){
    int num1 = 0; int num2 = 0;
    int t = 0;
    struct ListNode* t1 = l1;
    struct ListNode* t2 = l2;
    struct ListNode *res = (struct ListNode*)malloc(sizeof(struct ListNode));
    res->next = NULL;
    struct ListNode *s = res;
    for(int i=0 ; t1 != NULL || t2 != NULL || t != 0; i++) 
    {
        num1 = 0;
        num2 = 0;
        s->val = 0;
        if( t1 != NULL){
            s->val += t1->val;
            t1 = t1->next;
        }
        if( t2 != NULL){
            s->val += t2->val;
            t2 = t2->next;
        }
        s->val +=t;
        
        t = s->val/10;
        s->val = s->val % 10;
        
        if(t1 != NULL || t2 != NULL || t != 0){
            s->next = (struct ListNode*)malloc(sizeof(struct ListNode));
            s = s->next;
            s->next = NULL;
        }
    }
    return res;
}

C++

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
        ListNode* res = new ListNode(0);
        ListNode* p = res;
        ListNode* p1 = l1;
        ListNode* p2 = l2;
        int flag = 0;
        while(p1 || p2 ||flag){
            int tmp = 0;
            if (p1 != nullptr) tmp += p1->val;
            if (p2 != nullptr) tmp += p2->val;
            tmp += flag;

            flag = tmp / 10;
            tmp %= 10;
            ListNode* add = new ListNode(tmp);

            p->next = add;
            p = p->next;
            p1 = (p1 ? p1->next : nullptr);
            p2 = (p2 ? p2->next : nullptr);
        }
        return res->next;
    }
};

感谢点赞!!!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值