Accepted 32ms c++ solution, only two external variables.


  • 1
    class Solution {
    public:
        ListNode *addTwoNumbers(ListNode *l1, ListNode *l2) {
            if (l1 == NULL)
                return l2;
            else if (l2 == NULL)
                return l1;
    		ListNode *res = l1;
            int tmp = 0;
            while (true) {
    			if ((l1->val += l2->val + tmp) > 9) {
    				tmp = 1;
    				l1->val -= 10;
    			}
    			else
    				tmp = 0;
    			if (l1->next == NULL) {
    				l1->next = l2->next;
    				break;
    			}
                else if (l2->next == NULL)
                    break;
    			l1 = l1->next;
                l2 = l2->next;
            }
            while (l1->next != NULL && tmp) {
    			l1 = l1->next;
    			if ((l1->val += tmp) > 9) {
    				tmp = 1;
    				l1->val -= 10;
    			}
    			else
    				return res;
            }
    		if (tmp) {
    			l2->val = tmp;
    			l2->next = NULL;
    			l1->next = l2;
    		}
    		return res;
        }
    };

Log in to reply
 

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