# [2\. Add Two Numbers](https://leetcode.com/problems/add-two-numbers/) :::spoiler Solution ```cpp /** * 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 = new ListNode(); ListNode* cur = dummy; int carry = 0; while (l1 || l2 || carry) { int v1 = l1 ? l1->val : 0; int v2 = l2 ? l2->val : 0; int valSum = v1 + v2 + carry; carry = valSum / 10; valSum %= 10; cur->next = new ListNode(valSum); cur = cur->next; l1 = l1 ? l1->next : nullptr; l2 = l2 ? l2->next : nullptr; } return dummy->next; } }; ``` ``` - 時間複雜度:$O(\max(M, N))$ - 空間複雜度:$O(1)$ :::
×
Sign in
Email
Password
Forgot password
or
By clicking below, you agree to our
terms of service
.
Sign in via Facebook
Sign in via Twitter
Sign in via GitHub
Sign in via Dropbox
Sign in with Wallet
Wallet (
)
Connect another wallet
New to HackMD?
Sign up