445. 两数相加 II
题意
给你两个 非空 链表来代表两个非负整数。数字最高位位于链表开始位置。它们的每个节点只存储一位数字。将这两数相加会返回一个新的链表。
你可以假设除了数字 0 之外,这两个数字都不会以零开头。
样例输入
l1 = [7,2,4,3], l2 = [5,6,4]
样例输出
[7,8,0,7]
提示
链表的长度范围为 [1, 100]
0 <= node.val <= 9
输入数据保证链表代表的数字无前导 0
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) {
stack<int> s1, s2;
while(l1){
s1.push(l1->val);
l1 = l1->next;
}
while(l2){
s2.push(l2->val);
l2 = l2->next;
}
int carry = 0;
ListNode* head = nullptr, *tail = nullptr;
while(!s1.empty() || !s2.empty() || carry){
int n1 = s1.empty()? 0:s1.top();
int n2 = s2.empty()? 0:s2.top();
if(!s1.empty()) s1.pop();
if(!s2.empty()) s2.pop();
carry += n1 + n2;
if(head == nullptr){
tail = new ListNode(carry % 10);
head = new ListNode(0);
head->next = tail;
}else{
ListNode* temp = head->next;
head->next = new ListNode(carry % 10);
head->next->next = temp;
}
carry = carry / 10;
}
return head->next;
}
};
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]:
s1,s2 = [], []
while l1:
s1.append(l1.val)
l1 = l1.next
while l2:
s2.append(l2.val)
l2 = l2.next
head = tail = None
carry = 0
while s1 or s2 or carry:
n1 = s1.pop() if s1 else 0
n2 = s2.pop() if s2 else 0
carry += n1 + n2
if not head:
tail = ListNode(carry % 10)
head = ListNode(0)
head.next = tail
else:
temp = head.next
head.next = ListNode(carry % 10)
head.next.next = temp
carry = carry // 10
return head.next
备注
利用好栈的特性,使用head和tail两个结点可以应付所有创建列表的需要。python中的栈可以使用列表来实现。