One Pass O(1) space C++ code


  • 2
    /**
     * 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) {
             
             if (l1 == NULL) return l2;
             if (l2 == NULL) return l1;
            
             ListNode *p = l1, *q = l2, *r = NULL;
             int cur = 0;
             while (p != NULL && q != NULL) {
                 p->val += (q->val + cur);
                 cur = p->val / 10;
                 p->val %= 10;
                 r = p;
                 p = p->next;
                 q = q->next;
             }
             if (q != NULL) r->next = q;
             
             p = r->next;
             while (p != NULL) {
                 if (cur == 0) break;
                 p->val += cur;
                 cur = p->val / 10;
                 p->val %= 10;
                 r = p;
                 p = p->next;
             }
             if (cur != 0) {
                 q = (ListNode *)malloc(sizeof(ListNode));
                 q->next = NULL;
                 q->val = cur;
                 r->next = q;
             }
             return l1;
        }
    };

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.