两个链表元素相加,链表元素均为0~9的整数,把相加的结果返回给一个新的链表
struct LinkNode{
int val;
LinkNode *next;
LinkNode():val(0), next(nullptr){}
LinkNode(int x):val(x),next(nullptr){}
LinkNode(int x, LinkNode* node):val(x),next(node){}
};
LinkNode* solution(LinkNode *a1, LinkNode *a2){
//使用栈实现反转
stack<int> t1,t2;
if(a1 != nullptr){
t1.push_back(a1->val);
a1 = a1->next;
}
if(a2 != nullptr){
t2.push_back(a2->val);
a2 = a2->next;
}
int jinwei = 0;
//注意当进位位不为0,同时两个栈都为空,也是要把进位位给补上去的
while(!t1.empty() || !t2.empt() || jinwei != 0){
int temp1 = t1.empty() ? 0 : t1.top();
int temp2 = t2.empty() ? 0 :t2.top();
if(!t1.empty())
t1.pop();
if(!t2.empty())
t2.pop();
int ans = temp1 + temp2;
int mowei = ans %10;
jinwei = ans / 10;
LinkNode tempNode = new LinkNode(mowei);
tempNode->next = ans;
ans = TempNode;
}
return ans;
}
好久没写链表了,先连连手,熟悉熟悉
想想,自己写代码就是一坨屎
看到高手写的代码,简直就是一场盛宴
怎么搞
还能怎么搞?

该代码实现将两个链表中的元素相加,链表元素为0到9的整数,结果存储在新链表中。使用栈来辅助处理进位,遍历链表直至无元素且无进位。

被折叠的 条评论
为什么被折叠?



