类似于大数加法,两个链表相加得到一个新的链表
算法思想:首先想到的是肯定得从末尾进行相加,那就让两个链表的val值全部入栈,分别存在两个栈中,再依次弹栈相加,就是从末尾相加,需要注意的是可以定义一个进位bit,如果两个链表对应的val值相加大于等于十就将其置为1否则置为0;还有一个需要注意的地方是,由于我们是从末尾进行相加,所以每次拿到的都是新链表从后向前的结点,结点的连接需要注意,在最后两个链表相加完成后都会有一个bit值 需要对其进行判断是否为1,为1则需要再加一次,否则就不需要加额外的一次;
具体代码如下
/**
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
class Solution {
public:
/**
*
* @param head1 ListNode类
* @param head2 ListNode类
* @return ListNode类
*/
ListNode* addInList(ListNode* head1, ListNode* head2) {
// write code here
if(head1 == nullptr && head2 == nullptr)return nullptr;
else if(head1 == nullptr)return head2;
else if(head2 == nullptr)return head1;
stack<int>st1,st2;
ListNode* p = head1;
ListNode* q = head2;
ListNode* newhead = new ListNode(0);
ListNode*s = newhead;
int tmp = 0,bit = 0;
while(p != nullptr)
{
st1.push(p->val);
p = p->next;
}
while(q != nullptr)
{
st2.push(q->val);
q = q->next;
}
while(!st1.empty()&&!st2.empty())
{
//从前往后依次连接起来
int a = st1.top();st1.pop();
int b = st2.top();st2.pop();
tmp = (a+b+bit)%10;
if(a+b+bit>=10)bit = 1;
else bit = 0;
ListNode* Node = new ListNode(tmp);
Node->next = newhead->next;//刚开始是最后一个结点
newhead->next = Node;//保存当前Node,下一次循环进入时的结点的next就是当前结点
}
while(!st1.empty())
{
int a = st1.top();st1.pop();
tmp = (a+bit)%10;
if(a+bit>=10)bit = 1;
else bit = 0;
ListNode* Node= new ListNode(tmp);
Node->next = newhead->next;
newhead->next = Node;
}
while(!st2.empty())
{
int a = st2.top();st2.pop();
tmp = (a+bit)%10;
if(a+bit>=10)bit = 1;
else bit = 0;
ListNode* Node= new ListNode(tmp);
Node->next = newhead->next;
newhead->next = Node;
}
if(bit)
{newhead->val = 1;
return newhead;}
else
return newhead->next;
}
};