LeetCode 445两数相加IIMedium
- 题目简述:给你两个 非空 链表来代表两个非负整数。数字最高位位于链表开始位置。它们的每个节点只存储一位数字。将这两数相加会返回一个新的链表。你可以假设除了数字 0 之外,这两个数字都不会以零开头。
- 输入:(7 -> 2 -> 4 -> 3) + (5 -> 6 -> 4) 输出:7 -> 8 -> 0 -> 7
- 思路:反转链表后从低位到高位依次相加,最后再反转新求和链表并返回结果
class Solution {
public:
ListNode* ReverseList(ListNode *head)
{
if(head == nullptr || head->next == nullptr) return head;
ListNode *pre = NULL;
auto cur = head;
while(cur)
{
auto tmp = cur->next;
cur->next = pre;
pre = cur;
cur = tmp;
}
return pre;
}
ListNode* ReverseLists(ListNode *head)
{
if(head == nullptr || head->next == nullptr) return head;
ListNode *tail = ReverseLists(head->next);
head->next->next = head;
head->next = NULL;
return tail;
}
ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
auto rl1 = ReverseLists(l1);
auto rl2 = ReverseList(l2);
ListNode *dummy = new ListNode(-1);
int carry = 0;
auto cur = dummy;
while(rl1 || rl2)
{
int n1 = rl1 ? rl1->val : 0;
int n2 = rl2 ? rl2->val : 0;
int sum = n1 + n2 + carry;
carry = sum / 10;
cur->next = new ListNode(sum % 10);
cur = cur->next;
if(rl1) rl1 = rl1->next;
if(rl2) rl2 = rl2->next;
}
if(carry) cur->next = new ListNode(1);
return ReverseLists(dummy->next);
}
};
class Solution {
public:
ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
stack<int> st1, st2, res;
while(l1)
{
st1.push(l1->val);
l1= l1->next;
}
while(l2)
{
st2.push(l2->val);
l2 = l2->next;
}
int carry = 0;
while(!st1.empty() || !st2.empty())
{
int n1 = st1.empty() ? 0 : st1.top();
int n2 = st2.empty() ? 0 : st2.top();
int sum = n1 + n2 + carry;
carry = sum / 10;
res.push(sum % 10);
if(!st1.empty()) st1.pop();
if(!st2.empty()) st2.pop();
}
if(carry) res.push(1);
ListNode *dummy = new ListNode(-1);
auto cur = dummy;
while(!res.empty())
{
cur->next = new ListNode(res.top());
res.pop();
cur = cur->next;
}
return dummy->next;
}
};
class Solution {
public:
ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
stack<int> st1, st2;
while(l1)
{
st1.push(l1->val);
l1= l1->next;
}
while(l2)
{
st2.push(l2->val);
l2 = l2->next;
}
int carry = 0;
ListNode *dummy = new ListNode(-1);
while(!st1.empty() || !st2.empty() || carry != 0)
{
int n1 = st1.empty() ? 0 : st1.top();
int n2 = st2.empty() ? 0 : st2.top();
int sum = n1 + n2 + carry;
carry = sum / 10;
ListNode *cur = new ListNode(sum % 10);
cur->next = dummy->next;
dummy->next = cur;
if(!st1.empty()) st1.pop();
if(!st2.empty()) st2.pop();
}
return dummy->next;
}
};