From 958d567cb776e500dfad6d46044fb29f9b21b463 Mon Sep 17 00:00:00 2001 From: Yavuz Sava Date: Fri, 28 Mar 2025 20:20:50 +0000 Subject: [PATCH] =?UTF-8?q?main.cpp=20G=C3=BCncelle?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- main.cpp | 40 ++++++++++++++++++++++++++++++---------- 1 file changed, 30 insertions(+), 10 deletions(-) diff --git a/main.cpp b/main.cpp index 5dc233d..31a77b0 100644 --- a/main.cpp +++ b/main.cpp @@ -1,17 +1,37 @@ -#include -#include +/** + * 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: - std::vector twoSum(std::vector& nums, int target) { - std::unordered_map num_map; // Stores number and its index - for (int i = 0; i < nums.size(); ++i) { - int complement = target - nums[i]; - if (num_map.find(complement) != num_map.end()) { - return {num_map[complement], i}; // Found the two indices + 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 } - num_map[nums[i]] = i; // Store index of the current number + 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 {}; + + return dummy.next; // Return the result linked list } }; \ No newline at end of file