What is the problem of my code? memory limits excess


  • 0
    X
       /**
     * Definition for singly-linked list.
     * struct ListNode {
     *     int val;
     *     struct ListNode *next;
     * };
     */
    
    
    struct ListNode* addTwoNumbers(struct ListNode* l1, struct ListNode* l2) {
        struct ListNode* head1=l1;
        struct ListNode* head2=l2;
        struct ListNode* l_sum;
        struct ListNode* l_p, *l_temp;
        l_sum=NULL;
        int l_carry=0;
        int n=0;
        if (head1==NULL) return l2;
        if (head2==NULL) return l1;
        else{
                while (head1!=NULL || head2!=NULL || l_carry!=0){
                    n=n+1;
                    l_temp=(struct ListNode *)malloc(sizeof(struct ListNode));
                    
                    if(head1!=NULL && head2!=NULL) {
                        l_temp->val=l1->val+l2->val+l_carry;
                        head1=head1->next;
                        head2=head2->next;
                    }
                    else if(head1!=NULL && head2==NULL){
                        l_temp->val=l1->val+l_carry;
                        head1=head1->next;
                    }
                    else if(head1==NULL && head2!=NULL) {
                        l_temp->val=l2->val+l_carry;
                        head2=head2->next;
                    }
                    else l_temp->val=l_carry;
                                   
                    if(l_temp->val>=10){
                        l_temp->val=l_temp->val%10;
                        l_carry=1;
                    }
                    l_temp->next=NULL;
                    
                    if(n==1) {
                        l_sum=l_temp;
                        l_p=l_sum;
                    }
                    else {
                        l_p->next=l_temp;
                        l_p=l_p->next;
                    }
                }
                return(l_sum);
        } 
    }

Log in to reply
 

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