算法——两数相加

2两数相加

下面展示一些 内联代码片

复制代码
/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode() : val(0), next(nullptr) {}
 *     ListNode(int x) : val(x), next(nullptr) {}
 *     ListNode(int x, ListNode *next) : val(x), next(next) {}
 * };
 */
class Solution {
public:
    ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
        ListNode* sumhead = nullptr; // 初始化头指针为nullptr
        ListNode* current = nullptr; // 初始化当前节点为nullptr
        int c = 0; // 进位标志

        // 遍历两个链表,进行加法运算
        while (l1 != nullptr || l2 != nullptr || c > 0) {
            int x = (l1 != nullptr) ? l1->val : 0;
            int y = (l2 != nullptr) ? l2->val : 0;
            int tempSUM = x + y + c;

            // 处理进位
            if (tempSUM >= 10) {
                c = 1;
                tempSUM -= 10;
            } else {
                c = 0;
            }

            // 如果sumhead是nullptr,说明这是第一个节点
            if (!sumhead) {
                sumhead = new ListNode(tempSUM);//动态分配新节点
                current = sumhead;
            } else {
                // 否则,在current后面添加新节点
                current->next = new ListNode(tempSUM);
                current = current->next;
            }

            // 更新链表指针
            if (l1 != nullptr) l1 = l1->next;
            if (l2 != nullptr) l2 = l2->next;
        }

        return sumhead;
    }
};
相关推荐
Wilber的技术分享7 分钟前
【LeetCode高频手撕题 2】面试中常见的手撕算法题(小红书)
笔记·算法·leetcode·面试
邪神与厨二病10 分钟前
Problem L. ZZUPC
c++·数学·算法·前缀和
梯度下降中1 小时前
LoRA原理精讲
人工智能·算法·机器学习
IronMurphy1 小时前
【算法三十一】46. 全排列
算法·leetcode·职场和发展
czlczl200209252 小时前
力扣1911. 最大交替子序列和
算法·leetcode·动态规划
靴子学长2 小时前
Decoder only 架构下 - KV cache 的理解
pytorch·深度学习·算法·大模型·kv
寒秋花开曾相惜2 小时前
(学习笔记)3.8 指针运算(3.8.3 嵌套的数组& 3.8.4 定长数组)
java·开发语言·笔记·学习·算法
Гений.大天才2 小时前
2026年计算机领域的年度主题与范式转移
算法
njidf3 小时前
C++与Qt图形开发
开发语言·c++·算法
ZoeJoy83 小时前
算法筑基(一):排序算法——从冒泡到快排,一文掌握最经典的排序算法
数据结构·算法·排序算法