题目描述
假设链表中每一个节点的值都在 0 - 9 之间,那么链表整体就可以代表一个整数。
给定两个这种链表,请生成代表两个整数相加值的结果链表。
例如:链表 1 为 9->3->7,链表 2 为 6->3,最后生成新的结果链表为 1->0->0->0。
解法
先把两个链表的内容都放入栈中,然后把两个链表连起来(这是为了节约空间,最后把相加的结果放入原链表中,求和的结果所占链表结点数不会比两链表结点数之和还多),最后把两个栈相加的和放入第三个栈中,最后把第三个栈的内容放入链表中。
class Solution {
public:
ListNode* addInList(ListNode* head1, ListNode* head2) {
if(head1 == NULL) return head2;
if(head2 == NULL) return head1;
//将链表数值放入栈中
stack<int> st1, st2, st3;
ListNode *p;
p = head1;
st1.push((p->val));
while(p->next != NULL)
{
st1.push(p->next->val);
p = p->next;
}
//连接两个链表,这是为了将求和的结果放回到链表中,从而不占用其他空间
//求和的结果所占链表结点数不会比两链表结点数之和还多
p->next = head2;
p = head2;
while(p != NULL)
{
st2.push(p->val);
p = p->next;
}
//相加,个位和存入st3中
int temp = 0;
while(!st1.empty() && !st2.empty())
{
temp += st1.top() + st2.top();
if(temp >= 10)
{
st3.push(temp % 10);
temp = 1;
}
else
{
st3.push(temp);
temp = 0;
}
st1.pop();
st2.pop();
}
//若此时栈1不为空
if(!st1.empty())
{
while(!st1.empty())
{
temp += st1.top();
if(temp >= 10)
{
st3.push(temp % 10);
temp = 1;
}
else
{
st3.push(temp);
temp = 0;
}
st1.pop();
}
}
//若此时栈2不为空
if(!st2.empty())
{
while(!st2.empty())
{
temp += st2.top();
if(temp >= 10)
{
st3.push(temp % 10);
temp = 1;
}
else
{
st3.push(temp);
temp = 0;
}
st2.pop();
}
}
//把栈里内容放回链表中
p = head1;
p->val = st3.top();
st3.pop();
while(!st3.empty())
{
p = p->next;
p->val = st3.top();
st3.pop();
}
p->next = NULL;
return head1;
}
};
时间复杂度O(n)
空间复杂度O(n)