LeetCode学习笔记(1)第2题Add Two Numbers

题目: Add Two Numbers

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 contains a single digit. Add the two numbers and return the sum as a linked list.You may assume the two numbers do not contain any leading zero, except the number 0 itself.
在这里插入图片描述
在这里插入图片描述

分析

Special cases:
	1. two numbers have different lengths: e.g. 123 + 23233
	2. Sum has more digits: e.g. 11 + 99 = 110
Time complexity:  O(max(n, m))
Space complexity: O(max(n, m)):因为我们需要创建返回的列表

流程

1.创建一个dummy head list 用于存储返回的结果,并创建个tail指向dummy head.
2.用tail.next储存l1.val + l2.val的sum, 用carry保存可能存在的进位
3.循环l1, l2 并考虑进位,防止l1, l2 中最长的那个循环结束时,万一有进位,也要对其进行存储
4.返回list

在这里插入图片描述

代码

python版

# Definition for singly-linked list.
# class ListNode(object):
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next
class Solution(object):
    def addTwoNumbers(self, l1, l2):
        """
        :type l1: ListNode
        :type l2: ListNode
        :rtype: ListNode
        """
        dummy = tail = ListNode(0)
        sum = 0 #代码中carry用sum代替
        while l1 or l2 or sum:
            sum += (l1.val if l1 else 0) + (l2.val if l2 else 0)
            tail.next = ListNode(sum % 10)
            sum //= 10
            tail = tail.next
            l1 = l1.next if l1 else None
            l2 = l2.next if l2 else None
        return dummy.next
            

C++版

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode() : val(0), next(nullptr) {}
 *     ListNode(int x) : val(x), next(nullptr) {}
 *     ListNode(int x, ListNode *next) : val(x), next(next) {}
 * };
 */
class Solution {
public:
    ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
        ListNode dummy(0);
        ListNode* tail = &dummy;
        int sum = 0;
        while(l1 || l2 || sum){
            sum += (l1?l1->val:0) + (l2?l2->val:0);
            tail->next = new ListNode(sum % 10);
            sum /= 10;
            l1 = l1? l1->next:nullptr;
            l2 = l2? l2->next:nullptr;
            tail = tail->next;
        }
        return dummy.next;
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值