【数据结构】C语言实现两链表相加

以下是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。然后定义了创建节点和创建链表的函数createNodecreateList,以及打印链表的函数printList

接着定义了两个链表相加的函数addTwoNumbers,该函数使用了两个指针l1l2分别指向两个链表的头节点,使用一个循环遍历两个链表,将对应节点的值相加,并将结果存储到新的链表中。需要注意的是,如果相加的结果大于等于10,则需要进位。最后,如果最高位有进位,则需要在新链表的末尾添加一个节点。

最后,在main函数中创建两个链表,调用addTwoNumbers函数相加两个链表,并打印结果链表。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值