题目链接:2. Add Two Numbers
栈实现数字加法
C++
class Solution{
public:
ListNode* addTwoNumbers(ListNode* l1,ListNode* l2){
int sum=0;
ListNode* dummpy =new ListNode(0), *cur = dummpy;
while(l1||l2){
int val1 = l1?l1->val:0;
int val2 = l2?l2->val:0;
sum+=val1+val2;
cur->next =new ListNode(sum%10);
sum/=10;
cur = cur->next;
l1 = l1?l1->next:l1;
l2 = l2?l2->next:l2;
}
if(sum)cur->next= new ListNode(sum);
cur= dummpy->next;
delete dummpy;
return cur;
}
};
//C++
class Solution {
public:
ListNode* addTwoNumbers(ListNode*l1, ListNode*l2){
int carry =0;
ListNode* ans = new ListNode(-1);
ListNode* cur = ans;
while(l1||l2||carry){
int val = carry +(l1?l1->val:0)+(l2?l2->val:0);
l1 = l1?l1->next:l1;
l2 = l2?l2->next:l2;
carry = val/10;
cur->next = new ListNode(val%10);
cur=cur->next;
}
return ans->next;
}
};
Python
class Solution:
def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode:
ans = cur = ListNode(0)
sum =0
while l1 or l2 or sum:
if l1:sum+=l1.val; l1=l1.next
if l2:sum+=l2.val; l2=l2.next
cur.next = ListNode(sum%10)
sum//=10
cur=cur.next
return ans.next