2. 两数相加
题意
给你两个 非空 的链表,表示两个非负的整数。它们每位数字都是按照 逆序 的方式存储的,并且每个节点只能存储 一位 数字。
请你将两个数相加,并以相同形式返回一个表示和的链表。
你可以假设除了数字 0 之外,这两个数都不会以 0 开头。
样例输入
l1 = [2,4,3], l2 = [5,6,4]
样例输出
[7,0,8]
提示
每个链表中的节点数在范围 [1, 100] 内
0 <= Node.val <= 9
题目数据保证列表表示的数字不含前导零
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 *head = nullptr, *tail = nullptr;
int carry = 0;
while(l1 || l2){
int n1 = l1? l1->val:0;
int n2 = l2? l2->val:0;
int sum = n1 + n2 + carry;
if(!head){
head = tail = new ListNode(sum % 10);
}else{
tail->next = new ListNode(sum % 10);
tail = tail->next;
}
if(l1) l1 = l1->next;
if(l2) l2 = l2->next;
carry = sum / 10;
}
if(carry){
tail->next = new ListNode(carry);
tail = tail->next;
}
return head;
}
};
python代码
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def addTwoNumbers(self, l1: Optional[ListNode], l2: Optional[ListNode]) -> Optional[ListNode]:
cur = dummy = ListNode()
carry = 0
while l1 or l2 or carry:
n1 = l1.val if l1 else 0
n2 = l2.val if l2 else 0
carry += n1 + n2
cur.next = ListNode(carry % 10)
cur = cur.next
carry = carry // 10
if l1 : l1 = l1.next
if l2 : l2 = l2.next
return dummy.next
备注
列表遍历及列表创建