给你两个非空链表来代表两个非负整数。数字最高位位于链表开始位置。它们的每个节点只存储一位数字。将这两数相加会返回一个新的链表。(你可以假设除了数字 0 之外,这两个数字都不会以零开头)
Example:
输入:(7 -> 2 -> 4 -> 3) + (5 -> 6 -> 4)
输出:7 -> 8 -> 0 -> 7
解题思路:把两个链表当做两个栈,应用链表头插法
class Solution
{
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;
}
//定义carry记录进位
int carry=0;
ListNode *head=nullptr; //合成之后的链表头节点
while(!s1.empty() || !s2.empty() || carry!=0)
{
//出栈,定义a,b分别记录两个栈出栈的值
int a = s1.empty() ? 0 : s1.pop();
int b = s2.empty() ? 0 : s2.pop();
if(!s1.empty()) s1.pop();
if(!s2.empty()) s2.pop();
int sum = a+b+carry;
carry = sum/10; //记录进位,为1即进位,为0即不进位
sum %=10; //两数相加的结果值
ListNode node = new ListNode(sum);
//链表头插法,头插法为逆序建表
node->next=head;
head=node;
}
return head;
}
}