mirror of
https://github.com/Manoj-HV30/dsa-competitive-programming.git
synced 2026-05-16 19:35:22 +00:00
28 lines
857 B
C++
28 lines
857 B
C++
class Solution{
|
|
public:
|
|
ListNode* addTwoNumbers(ListNode* l1, ListNode* l2){
|
|
ListNode* dummyhead = new ListNode(0);
|
|
ListNode* tail = dummyhead;
|
|
bool carry = 0;
|
|
|
|
while(l1 || l2|| carry){
|
|
int digit1 = (l1!=nullptr) ? l1->val : 0;
|
|
int digit2 = (l2!=nullptr) ? l2->val : 0;
|
|
|
|
int sum = digit1+digit2+carry;
|
|
int digit = sum%10;
|
|
carry = sum/10;
|
|
|
|
ListNode* newnode = new ListNode*(digit);
|
|
tail->next = newnode;
|
|
tail = tail->next;
|
|
|
|
l1 = (l1!=nullptr) ? l1=>next : nullptr;
|
|
l2 = (l2!=nullptr) ? l2->next : nullptr;
|
|
}
|
|
ListNode* result = dummyhead->next;
|
|
delete dummyhead;
|
|
return result;
|
|
}
|
|
}
|