검색결과 리스트
add two numbers에 해당되는 글 1건
- 2020.06.11 [LeetCode][0002] Add Two Numbers
글
[LeetCode][0002] Add Two Numbers
LeetCode
2020. 6. 11. 08:44
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
ListNode *dummy = new ListNode(-1);
ListNode* target = dummy;
int carry = 0;
while(l1 || l2 || carry) {
int l1_val = (l1) ? (l1->val) : (0);
int l2_val = (l2) ? (l2->val) : (0);
int sum = (l1_val + l2_val + carry);
target->next = new ListNode(sum % 10);
carry = sum / 10;
target = target->next;
l1 = (l1) ? (l1->next) : (l1);
l2 = (l2) ? (l2->next) : (l2);
}
return dummy->next;
}
};