题目: 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;
}
};