Untitled
unknown
plain_text
2 years ago
1.7 kB
12
Indexable
/**
* 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) {
bool cf=false;
ListNode* p1=l1;
ListNode* p2=l2;
int v= p1->val + p2->val;
if(v>9) cf=1;
ListNode* head=new ListNode(v%10);
ListNode* dum=NULL;
ListNode* res=head;
p1=p1->next;
p2=p2->next;
while(p1!=NULL && p2!=NULL){
int v= p1->val + p2->val;
if(cf) v=v+1;
ListNode* dum = new ListNode(v%10);
head->next=dum;
head=head->next;
p1=p1->next;
p2=p2->next;
if(v>9) cf=true;
else cf=false;
}
while(p1!=NULL){
int v=p1->val;
if(cf) v++;
ListNode* dum = new ListNode(v%10);
head->next=dum;
head=head->next;
if(v>9) cf=true;
else cf=false;
p1=p1->next;
}
while(p2!=NULL){
int v=p2->val;
if(cf) v++;
ListNode* dum = new ListNode(v%10);
head->next=dum;
head=head->next;
p2=p2->next;
if(v>9) cf=true;
else cf=false;
}
if(cf){
ListNode* bo= new ListNode(1);
head->next=bo;
head=head->next;
}
return res;
}
};Editor is loading...