题目链接:https://leetcode-cn.com/problems/add-two-numbers-ii/
题目描述
给定两个非空链表来代表两个非负整数。数字最高位位于链表开始位置。它们的每个节点只存储单个数字。将这两数相加会返回一个新的链表。
你可以假设除了数字 0 之外,这两个数字都不会以零开头。
进阶:
如果输入链表不能修改该如何处理?换句话说,你不能对列表中的节点进行翻转。
示例:
输入: (7 -> 2 -> 4 -> 3) + (5 -> 6 -> 4)
输出: 7 -> 8 -> 0 -> 7
思路
转换成数字后相加-无法解决大数问题
忘记考虑溢出的问题了,放弃直接求和,改用大数问题的做法
class Solution {
public:
ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
if(!l1 || (!l1->next && l1->val == 0)) return l2;
if(!l2 || (!l2->next && l2->val == 0)) return l1;
unsigned long long num1 = 0, num2 = 0;
while (l1){
num1 = num1 * 10 + l1->val;
l1 = l1->next;
}
while (l2){
num2 = num2 * 10 + l2->val;
l2 = l2->next;
}
unsigned long long sum = num1 + num2;
ListNode *head = new ListNode(-1);
while (sum > 0){
ListNode * node = new ListNode(sum % 10);
sum /= 10;
node->next = head->next;
head->next = node;
}
return head->next;
}
};
1 栈
/*
* 用两个栈分别存储两个链表的翻转
* 弹栈并进行求和,将每一位的求和结果插入链表头
* 时间复杂度O(n)空间复杂度O(n)
*/
class Solution {
public:
ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
if(!l1) return l2;
if(!l2) return l1;
stack<int> st1, st2; // 用栈存储实现倒序
while (l1){
st1.push(l1->val);
l1 = l1->next;
}
while (l2){
st2.push(l2->val);
l2 = l2->next;
}
ListNode *head = new ListNode(-1);
int carry = 0; // 进位
while (!(st1.empty() && st2.empty())){
int num1 = 0, num2 = 0;
if(!st1.empty()){
num1 = st1.top();
st1.pop();
}
if(!st2.empty()){
num2 = st2.top();
st2.pop();
}
int sum = (num1 + num2 + carry) % 10;
carry = num1 + num2 + carry >= 10;
// 将求和后的位加入头部
ListNode *pNode = new ListNode(sum);
pNode->next = head->next;
head->next = pNode;
}
// 如果还有进位
if(carry){
ListNode *pNode = new ListNode(1);
pNode->next = head->next;
head->next = pNode;
}
return head->next;
}
};