本文已收录到:LeetCode刷题 专题
- 42. 接雨水 (Trapping Rain Water)
- [LeetCode] 2. 两数相加 2. Add Two Numbers
- [LeetCode] 19. 删除链表的倒数第N个节点 19. Remove Nth Node From End of List
- [LeetCode] 21. 合并两个有序链表(Merge Two Sorted Lists)
- [LeetCode] 24. 两两交换链表中的节点(Swap Nodes in Pairs)
- [LeetCode] 61. 旋转链表(Rotate List)
- [LeetCode] 82. 删除排序链表中的重复元素 II(Remove Duplicates from Sorted List II)
- [LeetCode] 83. 删除排序链表中的重复元素(Remove Duplicates from Sorted List)
- [LeetCode] 86. 分隔链表(Partition List)
- [LeetCode] 206. 反转链表(Reverse Linked List)
- [LeetCode] 92. 反转链表 II(Reverse Linked List II)
- [LeetCode] 147. 对链表进行插入排序(Insertion Sort List)
- [LeetCode] 203. 移除链表元素(Remove Linked List Elements)
- [LeetCode] 160. 相交链表(Intersection of Two Linked Lists)
- [LeetCode] 237. 删除链表中的节点 (Delete Node in a Linked List)
- [LeetCode] 328. 奇偶链表 (Odd Even Linked List)
- [LeetCode] 876. 链表的中间结点 (Middle of the Linked List)
- [LeetCode] 1290. 二进制链表转整数 (Convert Binary Number in a Linked List to Integer)
- [LeetCode] 141. 环形链表 (Linked List Cycle)
- [LeetCode] 142. 环形链表 II (Linked List Cycle II)
- [LeetCode] 283. 移动零 (Move Zeroes)
- [LeetCode] 496. 下一个更大元素 I (Next Greater Element I)
- [LeetCode] 503. 下一个更大元素 II (Next Greater Element II)
- [LeetCode] 456. 132模式 (132 Pattern)
- [LeetCode] 20. 有效的括号 (Valid Parentheses)
- [LeetCode] 94. 二叉树的中序遍历 (Binary Tree Inorder Traversal)
- [LeetCode] 144. 二叉树的前序遍历 (Binary Tree Preorder Traversal)
- [LeetCode] 145. 二叉树的后序遍历 (Binary Tree Postorder Traversal)
视频讲解
2. 两数相加 2. Add Two Numbers
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */ class Solution { public: ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) { ListNode dummy(0); ListNode* tail = &dummy; int sum = 0; while (l1 != nullptr || l2 != nullptr || sum > 0) { sum += l1->val + l2->val; l1 = l1 != nullptr ? l1->next : nullptr; l2 = l2 != nullptr ? l2->next : nullptr; tail->next = new ListNode(sum % 10); sum = sum / 10; tail = tail->next; } return dummy.next; } };
来源:LeetCode https://leetcode-cn.com/problems/add-two-numbers/
class Solution {
public:
ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
ListNode dummy(0); //虚拟结点
ListNode* tail = &dummy; //tail指针指向虚拟结点
int sum = 0;
while (l1 != nullptr || l2 !=nullptr || sum > 0) //必须都不满足才能停止循环
{
sum += (l1 == nullptr ? 0 : l1->val) + (l2 == nullptr ? 0 : l2->val);
l1 = l1 != nullptr ? l1->next : nullptr;
l2 = l2 != nullptr ? l2->next : nullptr;
//tail目前指向的虚拟节点
tail->next = new ListNode(sum % 10); //取个位
sum = sum / 10; //取十位
tail = tail->next;
}
return dummy.next;
}
};
第18行:
sum += l1->val + l2->val;
改为:
sum += (l1 == nullptr ? 0 : l1->val) + (l2 == nullptr ? 0 : l2->val);