This is my solution, move by points and didn't generate any note (avoid waste memory), could anybody tell me more beautiful code?


  • 0
    O

    This is my solution, move by points and didn't generate any note (avoid waste memory), could anybody tell me more beautiful code?

    /**
     * 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* l = l1;
            while(l->next != NULL) l = l->next;
            l->next = l2;
            l = l1;
            ListNode* ol;
            int jw = 0;
                while(l2 != NULL) {
                    if(l1->val == -1)
                        l1->val = l2->val + jw;
                    else
                        l1->val = l1->val + l2->val + jw;
                    l2->val = -1;
                    jw = 0;
                    if(l1->val >= 10) {
                        l1->val = l1->val % 10;
                        jw = 1;
                    }
                    ol = l1;
                    l1 = l1->next;
                    l2 = l2->next;
                }
                while(l1->val != -1) {
                    if(jw) {
                        l1->val += jw;
                        jw = 0;
                        if(l1->val >= 10) {
                            l1->val = l1->val % 10;
                            jw = 1;
                        }
                    }
                    ol = l1;
                    l1 = l1->next;
                }
                if(jw) {
                    l1->val = jw;
                    ol = l1;
                    l1 = l1->next;
                }
                ol->next = NULL;
            return l;
        }
    };
    

Log in to reply
 

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