力扣(LeetCode)2. 两数相加(C++\C)

模拟

模拟加法运算,设置进位数 t t t t = ( l 1 t=(l1 t=(l1-> v a l + l 2 val+l2 val+l2-> v a l + t ) % 10 val+t)\%10 val+t)%10 即为当前位上的数, t / 10 t/10 t/10 即是进位数。

设置哑结点,便于操作头结点。
模拟上述操作,最后返回哑结点的后继。

代码展示
class Solution {
public:
    ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
        int t = 0;//进位
        ListNode *dummy = new ListNode(0);
        auto cur = dummy;
        while(l1||l2){
            if(l1) t+=l1->val,l1 = l1->next;
            if(l2) t+=l2->val,l2 = l2->next;
            cur->next = new ListNode(t%10);//当前位的数
            cur = cur->next;
            t/=10;//进位数
        }
        if(t) cur->next = new ListNode(t);
        return dummy->next;
    }
};
//同时遍历两个链表
struct ListNode* addTwoNumbers(struct ListNode* l1, struct ListNode* l2) {
    struct ListNode* cur = (struct ListNode*)calloc(1, sizeof(struct ListNode));//声明一个链表,存储答案
    struct ListNode* dummyhead = (struct ListNode*)calloc(1, sizeof(struct ListNode));//哑结点,用于存储cur的值
    dummyhead = cur;
    int next = 0;//是否进位
    while (l1 && l2) {
        int sum = l1->val + l2->val + next;
        cur->next = (struct ListNode*)calloc(1, sizeof(struct ListNode));
        cur->next->val = sum % 10;
        if (sum >= 10) {
            next = 1;
        }
        else {
            next = 0;
        }
        cur = cur->next;
        l2 = l2->next, l1 = l1->next;//所有链表后移一位
    }
    while (l2) {//遍历结束,l2非空
        int sum = l2->val + next;
        cur->next = (struct ListNode*)calloc(1, sizeof(struct ListNode));
        cur->next->val = sum % 10;
        if (sum >= 10) {
            next = 1;
        }
        else {
            next = 0;
        }
        cur = cur->next;
        l2 = l2->next;
    }
    while (l1) {//遍历结束,l2非空
        int sum = l1->val + next;
        cur->next = (struct ListNode*)calloc(1, sizeof(struct ListNode));
        cur->next->val = sum % 10;
        if (sum >= 10) {
            next = 1;
        }
        else {
            next = 0;
        }
        cur = cur->next;
        l1 = l1->next;
    }
    if(next){
        cur->next = (struct ListNode*)calloc(1, sizeof(struct ListNode));
        cur->next->val = 1;
    }
    return dummyhead->next;
}
博主致语

理解思路很重要!
欢迎读者在评论区留言,作为日更博主,看到就会回复的。

AC

AC

复杂度分析
  1. 时间复杂度: O ( m a x ( m , n ) ) O(max(m,n)) O(max(m,n)) n n n l 1 l1 l1 的长度, m m m l 2 l2 l2 的长度,同时遍历 l 1 , l 2 l1,l2 l1,l2 , 一次遍历得到答案。
  2. 空间复杂度: O ( 1 ) O(1) O(1),除去保存答案所用空间,没有使用额外的线性空间。
  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

清墨韵染

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值