*Memory Limit Exceeded problem! help


  • 0
    X

    I am trying to use leecode to practice my C coding skill. Not very good at it.
    Below is my solution for the <Add Two Numbers> problem with C.
    But when I run it. It says Memory Limit Exceeded.
    Can anyone help me with that?
    Thanks in advanced.

    '''
    /**

    • Definition for singly-linked list.
      struct ListNode {
      int val;
      struct ListNode next;
      };
      /
      struct ListNode
      addTwoNumbers(struct ListNode
      l1, struct ListNode* l2) {

      struct ListNode* ret;

      struct ListNode* head;

      struct ListNode* l1_temp;
      struct ListNode* l2_temp;

      int x,y,sum,carry,val;

      ret=(struct ListNode*)malloc(sizeof(struct ListNode));

     head= ret;
     
     ret->val=0;
     ret->next=NULL;
    
    l1_temp=l1;
    l2_temp=l2;
    carry=0;
    while((l1_temp!= NULL)||(l2_temp!=NULL)){
        x= (l1_temp->next==NULL)? 0 :1;
        y= (l2_temp->next==NULL)? 0 :1;
        if ((x||y||carry)==0)
        {
            return ret;
        }
        
        sum=x+y+carry;
        carry=sum/10;
        val=sum%10;
        
        struct ListNode* pnew;
        pnew=(struct ListNode*)malloc(sizeof(struct ListNode));
        
        ret->val=val;
        ret->next=pnew;
        pnew->val=0;
        pnew->next=NULL;
        ret=pnew;
        
        
        l1_temp=l1->next;
        l2_temp=l2->next;
    }
    if((l1_temp== NULL)&&(l2_temp==NULL)&&carry){
        ret->val=1;
        ret->next=NULL;
    }
    
    return head;
    

    }
    '''


  • 0
    L

    Try running it a couple of times.


Log in to reply
 

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