Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /**
- * 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* root = new ListNode(0);
- ListNode* node = root;
- int carry = 0;
- while (l1 || l2)
- {
- int n1 = l1 ? l1->val : 0;
- int n2 = l2 ? l2->val : 0;
- int sum = n1 + n2 + carry;
- carry = sum / 10;
- node->next = new ListNode(sum % 10);
- node = node->next;
- if (l1) l1 = l1->next;
- if (l2) l2 = l2->next;
- }
- if (carry > 0)
- {
- node->next = new ListNode(carry);
- }
- return root->next;
- }
- };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement