C++ without allocating memory , but...


  • 0
    J
    ListNode* addTwoNumbers(ListNode* l1, ListNode* l2){
    	int bInc = 0;
    	int nTemp = 0;
    	ListNode* pCurr1 = l1;
    	ListNode* pCurr2 = l2;
    	ListNode* pLast1 = l1;
    	ListNode* pLast2 = l2;
    
    	for ( ; (pCurr1 != NULL) && (pCurr2 != NULL) ; pCurr1 = pCurr1->next, pCurr2 = pCurr2->next)
    	{
    		nTemp = pCurr1->val + pCurr2->val + bInc;
    		
    		//using ">" perhaps faster then "%"
    		if (nTemp >= 10)
    		{
    			nTemp -= 10;
    			bInc = 1;
    		}
    		else bInc = 0;
    		pCurr1->val = nTemp;
    		pCurr2->val = nTemp;
    		pLast1 = pCurr1;
    		pLast2 = pCurr2;
    	};
    
    	if (pCurr1 == NULL && pCurr2 == NULL)
    	{
    		if (bInc != 0)
    			pLast1->next = new ListNode(1);
    		return l1;
    	}
    	else if (pCurr2 == NULL)
    	{
    		if (bInc == 0) return l1;
    
    		for (; (bInc != 0) && (pCurr1 != NULL) ; pCurr1 = pCurr1->next )
    		{
    			nTemp = pCurr1->val + bInc;
    			if (nTemp >= 10)
    			{
    				nTemp -= 10;
    				bInc = 1;
    			}
    			else bInc = 0;
    			pCurr1->val = nTemp;
    			pLast1 = pCurr1;
    		}
    
    		if (bInc != 0)
    			pLast1->next = new ListNode(1);
    		return l1;
    	}
    	else
    	{
    		if (bInc == 0) return l2;
    
    		for (; (bInc != 0) && (pCurr2 != NULL); pCurr2 = pCurr2->next)
    		{
    			nTemp = pCurr2->val + bInc;
    			if (nTemp >= 10)
    			{
    				nTemp -= 10;
    				bInc = 1;
    			}
    			else bInc = 0;
    			pCurr2->val = nTemp;
    			pLast2 = pCurr2;
    		}
    
    		if (bInc != 0)
    			pLast2->next = new ListNode(1);
    		return l2;
    	}
    	return NULL;
    }
    

    }

    Testing need about 40ms , Why?
    
    1、Efficiency of allocated memory should not be lower?
    
    2、Can anyone help me optimize code?

  • 0
    F

    wow that's more complicated than necessary I feel


  • 0

Log in to reply
 

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