I wanna know the problem exists in my solution (there is a "memory limit exceed")


  • 0
    L
        /**
     * 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) {
            int carry=0;
            int valueOfFirstBit=(l1->val+l2->val+carry)%10;
            carry=(l1->val+l2->val+carry)/10;
            ListNode *head=new ListNode(valueOfFirstBit);
             ListNode *p=head;   
              l1++;l2++;
            while(l1&&l2){
                valueOfFirstBit=(l1->val+l2->val+carry)%10;
                carry=(l1->val+l2->val+carry)/10;
                p->next=new ListNode(valueOfFirstBit);
                l1++;
                l2++;
                
            }
            if(l2&&!l1) p->next=l1;
            else if(l1&&!l2) p->next=l2;
            else p->next=NULL;
            return head;
        }
    };

  • 1
    S

    When you move the pointer of the List, always use 'l = l->next' instead of 'l++'; You cannot assume that the nodes are stored consecutively in memory.


Log in to reply
 

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