Quick actions

cmd+k|ctrl+k

Navigation

Languages

adding two numbers

Snippet info

Language

C

Visibility

public

Author

krishnakanth

Created

2023-05-10T08:40:24.975498Z

Updated

2023-05-14T04:42:12.342172Z

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     struct ListNode *next;
 * };
 */
typedef struct ListNode node;

void insertion(node**head,node*list){
  node *t = *head ;
  if(!t){
    *head = list;
    return ;
  }
  while(t->next)
    t = t->next;

    t->next = list ;
    return ;
}
void reverse(node** ptr){
      node *temp ,*p,*n;
        temp = *ptr;
        p = NULL;
        while (temp != NULL) {
            n = temp->next ;
            temp->next = p;
            p = temp;
            temp = n;
        }
        *ptr = p;

      
}
node* operation(int a, int b,int*c){
      node *temp = (node*)malloc(sizeof(node)) ;
      
      int ran = a + b;
      temp->val = (ran + *c) <= 10 ? (ran + *c)%10 :  (ran + *c) - 10 ;
      temp->next = NULL;
      *c = (ran + *c) >= 10 ? 1: 0;
      // printf("%d %d\n",temp->val,ran );

      return temp ;
}
node* addTwoNumbers(node* l1, node* l2){
    node *head = NULL;
    // reverse(&l1);
    // reverse(&l2);
    int carry = 0;
    while(l1 || l2){
        
        if(l1 && l2){
          node *temp =  operation(l1->val, l2->val,&carry) ;
             insertion(&head,temp);    
        }else{
          if(l1){
            node *temp =  operation(l1->val, 0,&carry) ;
             insertion(&head,temp);    
              
          }else{
            node *temp =  operation(0, l2->val,&carry) ;
             insertion(&head,temp);    
              
          }
        }

        if (l1) {
          l1 = l1->next; 
        } 
        if (l2){ 
          l2 = l2->next; 
        }
        
         
    }
    if(carry == 1){
      node *temp =  operation(0, 0 ,&carry) ;
      insertion(&head,temp);    

    }

    

    return head;
}
INFO