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;
}
相关推荐
努力毕业的小土博^_^1 分钟前
【EI/Scopus双检索】2025年4月光电信息、传感云、边缘计算、光学成像、物联网、智慧城市、新材料国际学术盛宴来袭!
人工智能·神经网络·物联网·算法·智慧城市·边缘计算
神里流~霜灭22 分钟前
数据结构:二叉树(三)·(重点)
c语言·数据结构·c++·算法·二叉树·红黑树·完全二叉树
网安秘谈24 分钟前
非对称加密技术深度解析:从数学基础到工程实践
算法
luckyme_29 分钟前
leetcode-代码随想录-哈希表-有效的字母异位词
算法·leetcode·散列表
zh_xuan37 分钟前
LeeCode 57. 插入区间
c语言·开发语言·数据结构·算法
2401_8534482342 分钟前
C嘎嘎类里面的额函数
c语言·开发语言·c++
莫有杯子的龙潭峡谷1 小时前
4.4 代码随想录第三十五天打卡
c++·算法
luckyme_1 小时前
leetcode 代码随想录 数组-区间和
c++·算法·leetcode
好好学习^按时吃饭1 小时前
蓝桥杯2024年第十五届省赛真题-R 格式
算法·蓝桥杯
手握风云-1 小时前
优选算法的妙思之流:分治——快排专题
数据结构·算法