My C solution in 16ms


  • 1
    Y

    /**

    • Definition for singly-linked list.

    • struct ListNode {

    • int val;
      
    • struct ListNode *next;
      
    • };
      /
      struct ListNode
      addTwoNumbers(struct ListNode* l1, struct ListNode* l2) {
      struct ListNode *head_l1, *head_l2, *result_list, *result_head, *temp_result;
      int temp_val, up_val = 0;
      head_l1 = l1;
      head_l2 = l2;

      if (!l1 || !l2) {
      return NULL;
      }
      result_list = head_l1;
      result_head = head_l1;
      while (head_l1 && head_l2) {
      result_head = head_l1;
      temp_result = head_l2;
      temp_val = head_l1->val + head_l2->val + up_val;
      result_list->val = temp_val % 10;
      up_val = temp_val / 10;
      head_l1 = head_l1->next;
      head_l2 = head_l2->next;
      result_list = result_list->next;
      free(temp_result);
      temp_result = NULL;
      }

      while (head_l1) {
      result_head = head_l1;
      temp_val = head_l1->val + up_val;
      result_list->val = temp_val % 10;
      up_val = temp_val / 10;
      result_list = result_list->next;
      head_l1 = head_l1->next;
      }

      result_head->next = head_l2;
      result_list = head_l2;
      while (head_l2) {
      result_head = head_l2;
      temp_val = head_l2->val + up_val;
      result_list->val = temp_val % 10;
      up_val = temp_val / 10;
      head_l2 = head_l2->next;
      result_list = result_list->next;
      }
      if (up_val) {
      result_list = (struct ListNode*)malloc(sizeof(struct ListNode));
      result_list->val = up_val;
      result_list->next = NULL;
      result_head->next = result_list;
      }

      return l1;
      }


  • 0
    H

    too long to read。


Log in to reply
 

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