LeetCode 0002 - Add Two Numbers
# Hints
- 链表
# 题面
Difficulty | Time Complexity Limit | Extra-Memory Complexity Limit |
---|---|---|
Medium |
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 contain a single digit. Add the two numbers and return it as a linked list.
You may assume the two numbers do not contain any leading zero, except the number 0
itself.
Example:
Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
Explanation: 342 + 465 = 807.
# 题意
给定两个非空链表,每个链表表示一个非负整数,链表上的每个节点表示一个数位,表头为低位,表尾为高位。要求将两个非负整数相加,将结果用相同形式的链表表示,并返回表头指针。
# 题解
从表头到表尾依次相加即可。
细节问题:
注意特殊处理结果链表的头节点。
给定的两个链表不一定等长。
注意遍历完成后可能仍有进位,需要再新建一个节点。
# AC代码
/**
* 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 * head = nullptr;
// 主循环
ListNode * p = nullptr;
int rem = 0;
while (l1 != nullptr || l2 != nullptr) {
// 计算
int val1 = get_value(l1);
int val2 = get_value(l2);
int sum = val1 + val2 + rem;
int val = sum % 10;
rem = sum / 10;
// 插入
if (head == nullptr) {
head = new ListNode(val);
p = head;
} else {
p->next = new ListNode(val);
p = p->next;
}
// 递进
if (l1 != nullptr) l1 = l1->next;
if (l2 != nullptr) l2 = l2->next;
}
// 处理余数
if (rem > 0) {
p->next = new ListNode(rem);
p = p->next;
rem = 0;
}
// 返回
return head;
}
// 获取节点的值
inline int get_value(ListNode * p) {
return (p == nullptr ? 0 : p->val);
}
};
- 01
- Reading Papers - Kernel Concurrency06-01
- 02
- Linux Kernel - Source Code Overview05-01
- 03
- Linux Kernel - Per-CPU Storage05-01