模拟法思路解题,详细思路可以看leecode官方题解。
代码如下:
struct ListNode* addTwoNumbers(struct ListNode* l1, struct ListNode* l2) {
struct ListNode* dummy = malloc(sizeof(struct ListNode));
struct ListNode* tail = dummy;
int carry = 0;
while (l1 || l2) {
int sum = carry;
if (l1) {
sum += l1->val;
l1 = l1->next;
}
if (l2) {
sum += l2->val;
l2 = l2->next;
}
carry = sum / 10;
sum = sum % 10;
struct ListNode* newNode = malloc(sizeof(struct ListNode));
newNode->val = sum;
newNode->next = NULL;
tail->next = newNode;
tail = tail->next;
}
if (carry > 0) {
struct ListNode* newNode = malloc(sizeof(struct ListNode));
newNode->val = carry;
newNode->next = NULL;
tail->next = newNode;
}
struct ListNode* result = dummy->next;
free(dummy);
return result;
}
包含测试用例的本地完整运行代码如下:
#include <stdio.h>
#include <stdlib.h>
struct ListNode {
int val;
struct ListNode* next;
};
struct ListNode* addTwoNumbers(struct ListNode* l1, struct ListNode* l2) {
struct ListNode* dummy = malloc(sizeof(struct ListNode));
struct ListNode* tail = dummy;
int carry = 0;
while (l1 || l2) {
int sum = carry;
if (l1) {
sum += l1->val;
l1 = l1->next;
}
if (l2) {
sum += l2->val;
l2 = l2->next;
}
carry = sum / 10;
sum = sum % 10;
struct ListNode* newNode = malloc(sizeof(struct ListNode));
newNode->val = sum;
newNode->next = NULL;
tail->next = newNode;
tail = tail->next;
}
if (carry > 0) {
struct ListNode* newNode = malloc(sizeof(struct ListNode));
newNode->val = carry;
newNode->next = NULL;
tail->next = newNode;
}
struct ListNode* result = dummy->next;
free(dummy);
return result;
}
int main() {
// 创建测试用例链表 l1: [4, 5, 6]
struct ListNode* l1 = malloc(sizeof(struct ListNode));
l1->val = 4;
l1->next = malloc(sizeof(struct ListNode));
l1->next->val = 5;
l1->next->next = malloc(sizeof(struct ListNode));
l1->next->next->val = 6;
l1->next->next->next = NULL;
// 创建测试用例链表 l2: [4, 5, 1]
struct ListNode* l2 = malloc(sizeof(struct ListNode));
l2->val = 4;
l2->next = malloc(sizeof(struct ListNode));
l2->next->val = 5;
l2->next->next = malloc(sizeof(struct ListNode));
l2->next->next->val = 1;
l2->next->next->next = NULL;
// 调用 addTwoNumbers 函数进行链表相加
struct ListNode* result = addTwoNumbers(l1, l2);
// 遍历输出结果链表的值
printf("Result: ");
while (result) {
printf("%d ", result->val);
result = result->next;
}
printf("\n");
// 释放链表的内存
struct ListNode* curr = l1;
while (curr) {
struct ListNode* temp = curr;
curr = curr->next;
free(temp);
}
curr = l2;
while (curr) {
struct ListNode* temp = curr;
curr = curr->next;
free(temp);
}
return 0;
}