编辑代码

/**
 * Definition for singly-linked list.
 */

#include <stdio.h>
#include <stdlib.h>
#include <math.h> // 向下取整

struct ListNode {
  int val;
  struct ListNode *next;
};

// 20 ms
struct ListNode *addTwoNumbers(struct ListNode *l1, struct ListNode *l2) {
  if (l1 == NULL) { return l2; }
  if (l2 == NULL) { return l1; }
  struct ListNode *currListNode = (struct ListNode *)malloc(sizeof(struct ListNode));
  currListNode->next = NULL;
  struct ListNode *p = currListNode;
  int carry = 0;
  while (l1 || l2) {
    int num1 = (l1 == NULL) ? 0 : l1->val;
    int num2 = (l2 == NULL) ? 0 : l2->val;
    int sum = num1 + num2 + carry;
    carry = floor(sum / 10);
    struct ListNode *temp = (struct ListNode *)malloc(sizeof(struct ListNode));
    temp->val = sum % 10;
    temp->next = NULL;
    p->next = temp;
    p = p->next;

    if (l1 != NULL) l1 = l1->next;
    if (l2 != NULL) l2 = l2->next;
  }
  if (carry > 0) {
    struct ListNode *temp = (struct ListNode *)malloc(sizeof(struct ListNode));
    temp->val = carry;
    temp->next = NULL;
    p->next = temp;
  } 
  return currListNode->next;
}

// 以下是测试代码 -----------------------

void ToolPrintArray(int *array, int length) {
  printf("\n[");
  int lastIndex = length - 1;
  for (int i = 0; i < length; i++) {
    printf("%d", array[i]);
    if (i < lastIndex) {
      printf(", ");
    }
  }
  printf("]\n");
}

struct ListNode * create_node(int *list, int listSize) {
  if (list == NULL) return NULL;
  struct ListNode *resultNodel = NULL;
  int length = listSize - 1;
  for (int i = 0; i < listSize; i++) {
    struct ListNode *currListNode = (struct ListNode *)malloc(sizeof(struct ListNode));
    currListNode->val = list[length - i];
    if (i == 0) {
      currListNode->next = NULL;
    } else {
      currListNode->next = resultNodel;
    }
    resultNodel = currListNode;
  }
  return resultNodel;
}

void printStructList(struct ListNode *node) {
  if (!node) {
    printf("no valid value");
    return;
  }

  printf("\n结果:\n[");
  int start = 1;
  while (node)
  {
    if (start == 0) {
      printf(", ");
    }
    printf("%d", node->val);
    start = 0;
    node = node->next;
  }

  printf("]\n");
}

int main() {
  // int l1_list[] = {2,4,3};
  // int l2_list[] = {5,6,4};

  // int l1_list[] = {0};
  // int l2_list[] = {0};

  // int l1_list[] = {9,9,9,9,9,9,9};
  // int l2_list[] = {9,9,9,9};

  int l1_list[] = {9,9,9,9,9,9,9};
  int l2_list[] = {9,9,8};


  
  int *ttL1 = l1_list;
  int ttl1Len = sizeof(l1_list) / sizeof(l1_list[0]);
  printf("\n11 ttl1Len=%d", ttl1Len);
  int *ttL2 = l2_list;
  int ttl2Len = sizeof(l2_list) / sizeof(l2_list[0]);
  printf("\n22 ttl2Len=%d", ttl2Len);

  ToolPrintArray(ttL1, ttl1Len);
  ToolPrintArray(ttL2, ttl2Len);

  struct ListNode *l1 = create_node(ttL1, ttl1Len);
  struct ListNode *l2 = create_node(ttL2, ttl2Len);
  // printStructList(l1);
  // printStructList(l2);

  struct ListNode * resultNode = addTwoNumbers(l1, l2);
  printStructList(resultNode);
}