LeetCode //C - 2. Add Two Numbers

2. Add Two Numbers

You are given two non-empty linked lists representing two non-negative integers. The digits are stored in reverse order, and each of their nodes contains a single digit. Add the two numbers and return the sum as a linked list.

You may assume the two numbers do not contain any leading zero, except the number 0 itself.

Example 1:

Input: l1 = 2,4,3, l2 = 5,6,4
Output: 7,0,8
Explanation: 342 + 465 = 807.

Example 2:

Input: l1 = 0, l2 = 0
Output: 0

Example 3:

Input: l1 = 9,9,9,9,9,9,9, l2 = 9,9,9,9
Output: 8,9,9,9,0,0,0,1

Constraints:
  • The number of nodes in each linked list is in the range 1, 100.
  • 0 <= Node.val <= 9
  • It is guaranteed that the list represents a number that does not have leading zeros.

From: LeetCode

Link: 2. Add Two Numbers


Solution:

Ideas:

This function creates a dummy head for the result linked list, then iterates through both input lists l1 and l2. It adds corresponding digits along with any carry from the previous addition. If one list is longer than the other, it continues adding with the remaining digits. After the loop, if there is a carry left, it adds a new node with the carry value.

Code:
c 复制代码
/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     struct ListNode *next;
 * };
 */
struct ListNode* addTwoNumbers(struct ListNode* l1, struct ListNode* l2) {
    struct ListNode *dummyHead = (struct ListNode*) malloc(sizeof(struct ListNode));
    struct ListNode *current = dummyHead;
    int carry = 0;
    
    while (l1 != NULL || l2 != NULL || carry != 0) {
        int sum = carry;
        if (l1 != NULL) {
            sum += l1->val;
            l1 = l1->next;
        }
        if (l2 != NULL) {
            sum += l2->val;
            l2 = l2->next;
        }
        carry = sum / 10;
        current->next = (struct ListNode*) malloc(sizeof(struct ListNode));
        current = current->next;
        current->val = sum % 10;
    }
    
    current->next = NULL; // Terminate the list
    struct ListNode *result = dummyHead->next; // The result is in the next node after dummy head
    free(dummyHead); // Free the dummy head node
    return result;
}
相关推荐
Logic1011 小时前
C语言/数据结构字符串题解:按字符类型重排(数字→字母→符号)——三趟扫描稳定分区
c语言·数据结构·字符串·时间复杂度·计数排序·算法题·ascii
Logic1017 小时前
C语言/数据结构位运算题解:异或XOR找出学习计划中的“独特学习时间“——只出现一次的数字
c语言·数据结构·数组·位运算·时间复杂度·算法题·异或性质
wuminyu8 小时前
C++协程实现接收端的零拷贝Buffer管理原理剖析
java·linux·c语言·jvm·c++
小蒋学算法8 小时前
算法-交替删除操作后最后剩下的整数-跟着灵茶山艾府学算法
数据结构·算法
荆棘鸟智能8 小时前
林业遥感长势评估怎么做?从NDVI时序分析到LiDAR蓄积量回归
人工智能·算法·智慧林业
hhb_6189 小时前
AIRAGDebug:一键定位RAG链路异常
人工智能·python·算法
朝朝辞暮i9 小时前
C++ 第 6 课:switch —— 多状态选择
开发语言·c++·算法
苏打豆10 小时前
Pinocchio源码阅读——刚体运动物理量空间变换及求导
c++·线性代数·算法·矩阵·机器人
FluxArt10 小时前
GPT Image 2.5 中文提示词教程:Flux Art 可复用模板
前端·gpt·算法
思麟呀10 小时前
位运算:从一个整数到一个集合
c语言·数据结构·c++·算法