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;
}
相关推荐
纪元A梦22 分钟前
华为OD机试真题——斗地主之顺子(2025A卷:100分)Java/python/JavaScript/C/C++/GO最佳实现
java·c语言·javascript·c++·python·华为od
小陈爱建模1 小时前
2025东三省C题深圳杯C题数学建模挑战赛数模思路代码文章教学: 分布式能源接入配电网的风险分析
c语言·数学建模·能源
浅陌sss1 小时前
在VS2022中使用Lua与c交互(二)
c语言·lua
Lazyy.1 小时前
数据结构——树(中篇)
数据结构·算法
Darkwanderor1 小时前
快速上手c语言
c语言·开发语言
yuanManGan1 小时前
C++入门小馆: 模板
开发语言·c++·算法
C灿灿数模1 小时前
2025五一杯数学建模B题:矿山数据处理问题,详细问题分析,思路模型
算法·数学建模
Amctwd2 小时前
【排序算法】八大经典排序算法详解
python·算法·排序算法
2301_804774492 小时前
后缀数组~
数据结构·算法
序属秋秋秋2 小时前
《数据结构初阶》【顺序表/链表 精选15道OJ练习】
c语言·数据结构·c++·笔记·算法·链表