以下是C语言实现两个链表相加的示例代码:
#include <stdio.h>
#include <stdlib.h>
// 定义链表节点结构体
struct ListNode {
int val;
struct ListNode *next;
};
// 创建链表节点
struct ListNode* createNode(int val) {
struct ListNode* node = (struct ListNode*)malloc(sizeof(struct ListNode));
node->val = val;
node->next = NULL;
return node;
}
// 创建链表
struct ListNode* createList(int* nums, int numsSize) {
struct ListNode* head = NULL;
struct ListNode* tail = NULL;
for (int i = 0; i < numsSize; i++) {
struct ListNode* node = createNode(nums[i]);
if (head == NULL) {
head = node;
tail = node;
} else {
tail->next = node;
tail = node;
}
}
return head;
}
// 打印链表
void printList(struct ListNode* head) {
while (head != NULL) {
printf("%d ", head->val);
head = head->next;
}
printf("\n");
}
// 两个链表相加
struct ListNode* addTwoNumbers(struct ListNode* l1, struct ListNode* l2) {
struct ListNode* head = NULL;
struct ListNode* tail = NULL;
int carry = 0;
while (l1 != NULL || l2 != NULL) {
int val1 = l1 != NULL ? l1->val : 0;
int val2 = l2 != NULL ? l2->val : 0;
int sum = val1 + val2 + carry;
carry = sum / 10;
struct ListNode* node = createNode(sum % 10);
if (head == NULL) {
head = node;
tail = node;
} else {
tail->next = node;
tail = node;
}
if (carry > 0) {
struct ListNode* node = createNode(carry);
tail->next = node;
tail = node;
carry = 0;
}
if (l1 != NULL) l1 = l1->next;
if (l2 != NULL) l2 = l2->next;
}
return head;
}
int main() {
int nums1[] = {2, 4, 3};
int nums2[] = {5, 6, 4};
struct ListNode* l1 = createList(nums1, 3);
struct ListNode* l2 = createList(nums2, 3);
struct ListNode* result = addTwoNumbers(l1, l2);
printList(result);
return 0;
}
该代码中,首先定义了链表节点结构体struct ListNode
,包括节点值val
和指向下一个节点的指针next
。然后定义了创建节点和创建链表的函数createNode
和createList
,以及打印链表的函数printList
。
接着定义了两个链表相加的函数addTwoNumbers
,该函数使用了两个指针l1
和l2
分别指向两个链表的头节点,使用一个循环遍历两个链表,将对应节点的值相加,并将结果存储到新的链表中。需要注意的是,如果相加的结果大于等于10,则需要进位。最后,如果最高位有进位,则需要在新链表的末尾添加一个节点。
最后,在main
函数中创建两个链表,调用addTwoNumbers
函数相加两个链表,并打印结果链表。