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() : 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 step = 0;
- auto head = new ListNode();
- auto start = head;
- while(true){
- int sum = 0;
- if (l1 != nullptr) {
- sum += l1->val;
- l1 = l1->next;
- }
- if (l2 != nullptr){
- sum += l2->val;
- l2 = l2->next;
- }
- sum += step;
- step = sum / 10;
- head->val = sum % 10;
- if (l1 != nullptr || l2 != nullptr || step) {
- head->next = new ListNode();
- head = head->next;
- } else
- break;
- }
- return start;
- }
- };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement