C Solution


  • 0
    L

    Using typedef of struct ListNode as Node for brevity.

    void add_node (Node ** res, Node ** prev, Node * new_node) {
      if (*res && *prev)
        (*prev)->next = new_node;
      else
        *res = new_node;
      *prev = new_node;
    }
    
    int check_carry (node ** res_node, int tmp) {
      int carry;
    
      if (tmp >= 10) {
        tmp -= 10;
        carry = 1;
      } else {
         carry = 0;
      }
    
      (*res_node)->val = tmp;
      return carry;
    }
    
    int loop_remaining_side (Node ** res, Node ** prev, Node * lr, int carry) {
      int tmp;
      while (lr) {
        Node *res_node = (Node *) calloc (1, sizeof (Node));
        tmp = lr->val + carry;
        carry = check_carry (&res_node, tmp); 
    
        add_node (res, prev, res_node);
        lr = lr->next;
      }
    
      return carry;
    }
    
    /* Sum two linked lists into one */
    Node * add_with_lists (Node * a, Node * b) {
      int tmp;
      int carry = 0;
      node *res = NULL;
      node *prev = NULL;
    
      //  add both lists until one finishes
      while (a && b) {
        Node *res_node = (Node *) calloc (1, sizeof (Node));
    
        tmp = a->val + b->val + carry;
        carry = check_carry (&res_node, tmp); 
    
        add_node (&res, &prev, res_node);
        a = a->next;
        b = b->next;
      }
    
      // one list might be longer than the other, add it to the sum
      carry = loop_remaining_side (&res, &prev, a, carry);
      carry = loop_remaining_side (&res, &prev, b, carry);
    
      // we might need one more digit (ex, 1 + 99)
      if (carry) {
        Node *res_node = (Node *) calloc (1, sizeof (Node));
        res_node->val = 1;
        add_node (&res, &prev, res_node);
      }
    
      return res;
    }
    

Log in to reply
 

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