Exemplo n.º 1
0
 ListNode *addTwoNumbers(ListNode *l1, ListNode *l2) {
     int x=0, y=0, z=0;
     ListNode *h=NULL, *t=NULL;
     
     while (l1!=NULL || l2!=NULL){
         x = getValueAndMoveNext(&l1);
         y = getValueAndMoveNext(&l2);
         
         z = z + x + y;
         
         ListNode *node = new ListNode(z%10);
         if (h == NULL){
             h = t = node;
         }else{
             t->next = node;
             t = node;
         }
         
         z = z/10;
     }
     
     while (z > 0) {
         ListNode *node = new ListNode(z%10);
         t->next = node;
         z = z/10;
     }
     
     return h;
 }
Exemplo n.º 2
0
    ListNode *addTwoNumbers(ListNode *l1, ListNode *l2) 
	{
        int x=0, y=0, carry=0, sum=0;
        ListNode *h=NULL, **t=&h;
        
        while (l1!=NULL || l2!=NULL)
		{
			//如果l后面没有节点了,就假设有节点,返回值为0
            x = getValueAndMoveNext(l1);
            y = getValueAndMoveNext(l2);
            
            sum = carry + x + y;
            
            ListNode *node = new ListNode(sum%10);
            *t = node;
            t = (&node->next);
            
            carry = sum/10;
        }
        
        if (carry > 0) 
		{
            ListNode *node = new ListNode(carry%10);
            *t = node;
        }
        
        return h;
    }
Exemplo n.º 3
0
ListNode *calculateNext(ListNode **node, ListNode **l1, ListNode **l2)
{
    int value1 = getValueAndMoveNext(l1);
    int value2 = getValueAndMoveNext(l2);

    int sum = value1 + value2 + (*node)->val;
    if (sum >= 10)
    {
        (*node)->val = sum % 10;
        (*node)->next = new ListNode(1);
    }
    else
    {
        (*node)->val = sum;
        (*node)->next = new ListNode(0);
    }

    return *node;
}