- Big integer sumμ linked list ννλ‘ λ³κ²½ν΄μ λμ¨ λ¬Έμ .
/**
* 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;
ListNode* prev = &head;
int carry = 0;
while (l1 != nullptr || l2 != nullptr) {
int sum = carry;
if (l1 != nullptr) {
sum += l1->val;
l1 = l1->next;
}
if (l2 != nullptr) {
sum += l2->val;
l2 = l2->next;
}
carry = sum >= 10? 1 : 0;
ListNode* curr = new ListNode(sum % 10);
prev->next = curr;
prev = curr;
}
if (carry > 0) {
prev->next = new ListNode(1);
}
return head.next;
}
};