week15
题目
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.
原题地址:https://leetcode.com/problems/add-two-numbers-ii/description/
解析
题目要求以链表形式给出两个数,求这两个数的和,同样以链表形式给出结果。
大致思路是将表示同一个数的每一位的链表中的元素存入栈中,将两个加数的相同位从各自的栈中取出,相加,记录和以及进位,进位作为下一位的数相加时的一个输入。
详细过程参考下面代码及注释
代码
class Solution {
public:
ListNode * addTwoNumbers(ListNode* l1, ListNode* l2) {
/* 用来记录两个数的每一位 */
stack<int> s1, s2;
/* 保存相加结果的每一位 */
stack<int> s;
ListNode* tmp;
tmp = l1;
/* 将链表中的元素转移到栈中,方便后面相加 */
while (tmp != NULL) {
s1.push(tmp->val);
tmp = tmp->next;
}
tmp = l2;
while (tmp != NULL) {
s2.push(tmp->val);
tmp = tmp->next;
}
int length1 = s1.size();
int length2 = s2.size();
int num1, num2;
int carry = 0;
/* 第一个数的长度小于或等于第二个数的情况 */
if (length1 <= length2) {
/* 将两个数的相同位相加 */
for (int i = 0; i < length1; ++i) {
num1 = s1.top();
num2 = s2.top();
/* 除了加上当前位置两个数对应的位的数,还要加上上一位的进位 */
s.push((num1 + num2 + carry) % 10);
carry = (num1 + num2 + carry) / 10;
s1.pop();
s2.pop();
}
for (int i = 0; i < length2 - length1; ++i) {
num2 = s2.top();
s.push((num2 + carry) % 10);
carry = (num2 + carry) / 10;
s2.pop();
}
}
/* 第一个数的长度大于第二个数的情况 */
else {
for (int i = 0; i < length2; ++i) {
num1 = s1.top();
num2 = s2.top();
s.push((num1 + num2 + carry) % 10);
carry = (num1 + num2 + carry) / 10;
s1.pop();
s2.pop();
}
for (int i = 0; i < length1 - length2; ++i) {
num1 = s1.top();
s.push((num1 + carry) % 10);
carry = (num1 + carry) / 10;
s1.pop();
}
}
/* 如果最高位有进位,结果需要新增一位数 */
if (carry == 1) {
s.push(carry);
}
ListNode* rel;
ListNode* temp;
/* 需要结果第一位的指针,将第一位特殊处理 */
if (!s.empty()) {
rel = new ListNode(s.top());
temp = rel;
s.pop();
}
/* 将栈中保存的结果的每一位链接成新的链表 */
while (!s.empty()) {
temp->next = new ListNode(s.top());
temp = temp->next;
s.pop();
}
return rel;
}
};