LeetCode-2.Add_Two_Numbers_.../main.cpp
2025-03-28 20:20:50 +00:00

37 lines
1.3 KiB
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) {
ListNode dummy(0); // Dummy node to simplify result list creation
ListNode* p = &dummy; // Pointer to build the new list
int carry = 0; // To track the carry from additions
while (l1 != nullptr || l2 != nullptr || carry) {
int sum = carry;
if (l1 != nullptr) {
sum += l1->val; // Add value from l1 if not reached its end
l1 = l1->next; // Move to the next node in l1
}
if (l2 != nullptr) {
sum += l2->val; // Add value from l2 if not reached its end
l2 = l2->next; // Move to the next node in l2
}
carry = sum / 10; // Calculate the carry
p->next = new ListNode(sum % 10); // Create a new node with the digit value
p = p->next; // Move pointer to the newly created node
}
return dummy.next; // Return the result linked list
}
};