445. Add Two Numbers II**
https://leetcode.com/problems/add-two-numbers-ii/
题目描述
You are given two non-empty linked lists representing two non-negative integers. The most significant digit comes first 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.
Follow up:
What if you cannot modify the input lists? In other words, reversing the lists is not allowed.
Example:
Input: (7 -> 2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 8 -> 0 -> 7
C++ 实现 1
先用 Reverse 的方法. 之后再考虑不修改输入节点的方法.
class Solution {
private:
ListNode* reverse(ListNode *head) {
ListNode *pre = nullptr;
auto ptr = head;
while (ptr) {
ListNode *tmp = ptr->next;
ptr->next = pre;
pre = ptr;
ptr = tmp;
}
return pre;
}
public:
ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
l1 = reverse(l1);
l2 = reverse(l2);
int carry_over = 0;
ListNode *dummy = new ListNode(0);
auto ptr = dummy;
while (l1 || l2 || carry_over) {
int part1 = l1 ? l1->val : 0;
int part2 = l2 ? l2->val : 0;
int sum = carry_over + part1 + part2;
ptr->next = new ListNode(sum % 10);
ptr = ptr->next;
carry_over = sum / 10;
l1 = l1 ? l1->next : nullptr;
l2 = l2 ? l2->next : nullptr;
}
return reverse(dummy->next);
}
};
C++ 实现 2
想不修改输入节点, 需要使用栈.
class Solution {
private:
// 传递指针是可以修改原节点的
void insert(ListNode *head, int val) {
ListNode *node = new ListNode(val);
node->next = head->next;
head->next = node;
}
public:
ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
stack<int> s1, s2;
while (l1) {
s1.push(l1->val);
l1 = l1->next;
}
while (l2) {
s2.push(l2->val);
l2 = l2->next;
}
int carry_over = 0;
ListNode *dummy = new ListNode(0);
while (!s1.empty() || !s2.empty() || carry_over) {
int part1 = 0, part2 = 0;
if (!s1.empty()) {
part1 = s1.top();
s1.pop();
}
if (!s2.empty()) {
part2 = s2.top();
s2.pop();
}
int sum = part1 + part2 + carry_over;
insert(dummy, sum % 10);
carry_over = sum / 10;
}
return dummy->next;
}
};