class Solution {
public:
ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
ListNode* head = NULL,* tail = NULL;
int arry = 0;
while(l1||l2){
int n1 = l1?l1->val:0;
int n2 = l2?l2->val:0;
int num = n1+n2+arry;
if(!head){
head = tail = new ListNode(num % 10);
}
else{
tail->next = new ListNode(num%10);
tail = tail->next;
}
arry = num/10;
if(l1){
l1 = l1->next;
}
if(l2){
l2 = l2->next;
}
}
if(arry>0){
tail->next = new ListNode(arry);
}
return head;
}
};
C/C++单链表两数相加LeetCode
最新推荐文章于 2024-07-19 14:27:26 发布