1.题目
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.
2.思路
1.要考虑有进位的情况 比如十进制 “/10” 以及“%10”
2. 创建一个新的链表来接受结果,最后返回头节点即可
3.代码
#include <iostream>
#include <memory>
using namespace std;
struct ListNode {
int val;
ListNode* next;
ListNode(int x) : val(x), next(nullptr) {}
};
class Solution {
public:
ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
// 要设置加法的标志位 node的值在0-9 之间 加的值/10 为 标志位满
//特殊情况就是当到了链表的最后一个节点了 加法标志位仍然为1 要像结果最后面加个1
int flag = 0 ;
ListNode* dummy = new ListNode(0); //创建虚拟的头节点
ListNode* cur = dummy; //使用指针指向
while (l1 != nullptr || l2 != nullptr)
{
int sum = flag;
if (l1 != nullptr)
{
sum += l1->val ;
l1 = l1->next;
}
if (l2 != nullptr)
{
sum += l2->val ;
l2 = l2->next;
}
flag = (sum / 10);
cur->next = new ListNode(sum%10);
cur = cur->next;
}
if (flag > 1)
{
cur->next = new ListNode(flag);
}
return dummy->next; //返回真正的头节点
}
};
int main() {
// 创建第一条链表:2 -> 4 -> 3
ListNode* l1 = new ListNode(2);
l1->next = new ListNode(4);
l1->next->next = new ListNode(3);
// 创建第二条链表:5 -> 6 -> 4
ListNode* l2 = new ListNode(5);
l2->next = new ListNode(6);
l2->next->next = new ListNode(4);
Solution s1;
// 输出结果链表
ListNode* result = s1.addTwoNumbers(l1, l2);
while (result != nullptr) {
std::cout << result->val << " ";
result = result->next;
}
std::cout << std::endl;
return 0;
}
4.总结
1.如何创建新的节点,以及遍历链表
747

被折叠的 条评论
为什么被折叠?



