【LeetCode】剑指 Offer II 025. 链表中的两数相加
class Solution {
public:
ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
ListNode * ans = new ListNode,*pre=nullptr,*temp;
stack<int> s1,s2;
int la=0,lb=0;
while(l1){
s1.push(l1->val);
++la;
l1=l1->next;
}
while(l2){
s2.push(l2->val);
++lb;
l2=l2->next;
}
int nm=0,flag=1,minL=lb;
int val=la-lb;
if(val<0){
val=-val;
minL=la;
flag=0;
}
for(int i=0;i!=minL;++i){
temp=new ListNode(s1.top()+s2.top()+nm,pre);
nm=temp->val/10;
temp->val%=10;
ans->next=temp;
pre=temp;
s1.pop();
s2.pop();
}
if(flag)
while(val--)
{
temp=new ListNode(s1.top()+nm,pre);
nm=temp->val/10;
temp->val%=10;
ans->next=temp;
pre=temp;
s1.pop();
}
else
while(val--)
{
temp=new ListNode(s2.top()+nm,pre);
nm=temp->val/10;
temp->val%=10;
ans->next=temp;
pre=temp;
s2.pop();
}
if(nm){
temp=new ListNode(nm,pre);
ans->next=temp;
}
return ans->next;
}
};
思路1:栈+模拟(以上代码)
思路2:链表翻转相加再翻转
思路3:链表转数字,相加结果再转链表

浙公网安备 33010602011771号