# 0002. Add Two Numbers ###### tags: `Leetcode` `Medium` `Linked List` `Add Simulation` Link: https://leetcode.com/problems/add-two-numbers/ ## 思路 挺简单的一题,直接上code 方法一是新建了一个linked list存结果 方法二是直接用l2的空间存 ## Code ### 方法一 ```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 *head = nullptr; ListNode *tail = nullptr; int carry = 0; if(!l1){ return l2; } if(!l2){ return l1; } while(l1||l2){ int n1 = l1?l1->val:0; int n2 = l2?l2->val:0; int sum = n1+n2+carry; if(!head){ head = tail = new ListNode(sum%10); } else{ tail->next = new ListNode(sum%10); tail = tail->next; } carry = sum/10; if(l1){ l1 = l1->next; } if(l2){ l2 = l2->next; } } if(carry>0){ tail->next = new ListNode(carry); tail = tail->next; } return head; } }; ``` ### 方法二 ```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) { int carry = 0; if(!l1){ return l2; } if(!l2){ return l1; } ListNode *head = l2; ListNode *tail = nullptr; while(l1||l2){ int n1 = l1?l1->val:0; int n2 = l2?l2->val:0; int sum = n1+n2+carry; if(l2){ l2->val = sum%10; tail = l2; } else{ if(!tail){ tail = new ListNode(sum%10); } else{ tail->next = new ListNode(sum%10); // l1 = before->next; tail = tail->next; } } carry = sum/10; if(l1){ l1 = l1->next; } if(l2){ l2 = l2->next; } } if(carry>0){ tail->next = new ListNode(carry); tail = tail->next; } return head; } }; ``` ## Result ### 方法一 Runtime: 20 ms, faster than **91.37%** of C++ online submissions for Add Two Numbers. Memory Usage: 71.3 MB, less than **17.68%** of C++ online submissions for Add Two Numbers. ### 方法二 Runtime: 28 ms, faster than **61.98%** of C++ online submissions for Add Two Numbers. Memory Usage: 71 MB, less than **91.19%** of C++ online submissions for Add Two Numbers.