[C++] Share my long code! It's long but clear


  • 0

    First, traverse the two list, and then the longer one, Lastly, to cope with the carry bit

    ListNode* addTwoNumbers(ListNode* l1, ListNode* l2)
    	{
    		int temp = 0;
    		ListNode* l3 = NULL;
    		ListNode* p = l3;
    
    		while(l1&&l2)
    		{
    			int sum = l1->val + l2->val + temp;
    			temp = sum / 10;
    
    			ListNode* l3_ptr = new ListNode(sum % 10);
    			if(l3 == NULL)
    			{
    				l3 = l3_ptr;
    				p = l3;
    			}
    			else
    			{
    				p->next = l3_ptr;
    				p = p->next;
    			}
    
    
    			l1 = l1->next;
    			l2 = l2->next;
    		}
    		while(l1)
    		{
    			int sum = l1->val + temp;
    			temp = sum / 10;
    
    			ListNode* l3_ptr = new ListNode(sum % 10);
    			if(l3 == NULL)
    			{
    				l3 = l3_ptr;
    				p = l3;
    			}
    			else
    			{
    				p->next = l3_ptr;
    				p = p->next;
    			}
    
    			l1 = l1->next;
    		}
    		while(l2)
    		{
    			int sum = l2->val + temp;
    			temp = sum / 10;
    
    			ListNode* l3_ptr = new ListNode(sum % 10);
    			if(l3 == NULL)
    			{
    				l3 = l3_ptr;
    				p = l3;
    			}
    			else
    			{
    				p->next = l3_ptr;
    				p = p->next;
    			}
    
    
    			l2 = l2->next;
    		}
    		if(temp)
    		{
    			ListNode* l3_ptr = new ListNode(temp);
    			if(l3 == NULL)
    			{
    				l3 = l3_ptr;
    				p = l3;
    			}
    
    			p->next = l3_ptr;
    		}
    		return l3;
    	}
    
    

Log in to reply
 

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