【LeetCode】2. Add Two Numbers C语言

本文介绍了一个LeetCode经典题目“两数相加”的解决方案,该题要求使用链表来表示两个非负整数并进行相加操作。通过C语言实现,详细展示了如何遍历两个链表节点,处理进位逻辑,并最终返回相加结果的链表。

LeetCode解题小结:

原题:给定两个非空的链表,表示两个非负整数。 数字以相反的顺序存储,每个节点包含一个数字。 两个数字相加,并将结果作为链表返回。

注意:

两个数字是反向存储相加的例如:342+465=807。

                    Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
                    Output: 7 -> 0 -> 8

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     struct ListNode *next;
 * };
 */

struct ListNode* addTwoNumbers(struct ListNode* l1, struct ListNode* l2) {
    
    struct ListNode *p1=l1;
    struct ListNode *p2=l2;
    struct ListNode *result=(struct ListNode *)malloc(sizeof(struct ListNode));
    result->val=0;

    struct ListNode *p=NULL;
    int c=0;
    while (p1!=NULL || p2!=NULL || c!=0)
    {
        if(p == NULL)
        {
            p=result;
        }
        else
        {
            p->next=(struct ListNode*)malloc(sizeof(struct ListNode)); //这里写成p会出错
            p->next->val=0;
            p=p->next;
        }
        int a=(p1==NULL ? 0:p1->val);
        int b=(p2==NULL ? 0:p2->val);
        int s=(a+b+c)%10;
        c=(a+b+c)/10;
        p->val=s;     
        p->next=NULL;
   
        p1=(p1==NULL ? NULL : p1->next);
        p2=(p2==NULL ? NULL : p2->next);

    }
    return result;
} 


LeetCode 题目2《两数相加》是一道经典的算法题目,主要涉及基本的数组操作和整数计算,目标是给定两个非负整数,通过栈的数据结构来求它们的和。以下是使用 C 语言的一个简单解决方案: ```c #include <stdio.h> // 定义一个结构体存放链表节点 typedef struct ListNode { int val; struct ListNode *next; } ListNode; // 将输入的十进制数字转换成链表表示形式 ListNode* createListNode(int num) { ListNode* head = (num == 0) ? NULL : &head; while (num > 0) { head->val = num % 10; num /= 10; head = head->next; if (head == NULL) { head = (ListNode*)malloc(sizeof(ListNode)); head->next = NULL; } } return head; } // 将链表表示的两个数相加并返回结果链表 ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) { ListNode dummy(0), *curr = &dummy; int carry = 0; while (l1 != NULL || l2 != NULL) { int a = (l1 != NULL) ? l1->val : 0; int b = (l2 != NULL) ? l2->val : 0; int sum = a + b + carry; carry = sum / 10; // 计算进位 curr->next = createListNode(sum % 10); // 创建新的结点存储当前位的值 curr = curr->next; if (l1 != NULL) { l1 = l1->next; } if (l2 != NULL) { l2 = l2->next; } } // 如果最后还有进位,则在链表末尾添加一个结点表示 if (carry > 0) { curr->next = createListNode(carry); } return dummy.next; } int main() { ListNode* l1 = createListNode(2); l1->next = createListNode(4); l1->next->next = createListNode(3); ListNode* l2 = createListNode(5); l2->next = createListNode(6); l2->next->next = createListNode(4); ListNode* result = addTwoNumbers(l1, l2); while (result != NULL) { printf("%d", result->val); result = result->next; } return 0; } ``` 这个程序首先将两个输入的整数转换成链表的形式,然后逐位相加,每一步都处理了进位的情况,并保持链表结构。最终得到的结果也是一个链表
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值