原题链接:Leetcode445. 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 contains a single digit. Add the two numbers and return the sum as a linked list.
You may assume the two numbers do not contain any leading zero, except the number 0 itself.
Example 1:
Input: l1 = [7,2,4,3], l2 = [5,6,4]
Output: [7,8,0,7]
Example 2:
Input: l1 = [2,4,3], l2 = [5,6,4]
Output: [8,0,7]
Example 3:
Input: l1 = [0], l2 = [0]
Output: [0]
Constraints:
- The number of nodes in each linked list is in the range [1, 100].
- 0 <= Node.val <= 9
- It is guaranteed that the list represents a number that does not have leading zeros.
Follow up: Could you solve it without reversing the input lists?
方法一:栈
思路:
两个数是在链表中逆序存储的,而计算的时候需要把顺序倒回来,因此就想到栈。
其余的部分正常模拟即可
C++代码:
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode() : val(0), next(nullptr) {}
* ListNode(int x) : val(x), next(nullptr) {}
* ListNode(int x, ListNode *next) : val(x), next(next) {}
* };
*/
class Solution {
public:
ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
stack<int> st1, st2; // 设置两个栈用于逆序存数
int carry = 0; // 进位
ListNode* ans = nullptr;
// 将两个数存入栈中
while(l1){
st1.push(l1->val);
l1 = l1->next;
}
while(l2){
st2.push(l2->val);
l2 = l2->next;
}
while(!st1.empty() || !st2.empty() || carry > 0){
int a = st1.empty() ? 0 : st1.top();
int b = st2.empty() ? 0 : st2.top();
if(!st1.empty()) st1.pop();
if(!st2.empty()) st2.pop();
int cur = a + b + carry;
carry = cur / 10;
cur = cur % 10;
// 创建一个新节点
auto cur_node = new ListNode(cur);
cur_node -> next = ans;
ans = cur_node;
}
return ans;
}
};
复杂度分析:
- 时间复杂度:O(n),数的位数,两个数的每位都会被遍历一次
- 空间复杂度:O(n) ,用于存两个数的栈