链接:
题目:
给定两个 非空链表 l1和 l2 来代表两个非负整数。数字最高位位于链表开始位置。它们的每个节点只存储一位数字。将这两数相加会返回一个新的链表。
可以假设除了数字 0 之外,这两个数字都不会以零开头。
解题:
利用堆栈来存储链表的值。
加法中,两数和的余数是个位,除数是十位。
class Solution {
public:
/**
*
* @param head1 ListNode类
* @param head2 ListNode类
* @return ListNode类
*/
ListNode* addInList(ListNode* head1, ListNode* head2) {
// write code here
stack<int> s1;
stack<int> s2;
stack<int> result;
while(head1){
s1.push(head1->val);
head1=head1->next;
}
while(head2){
s2.push(head2->val);
head2=head2->next;
}
int high=0;//进位
while(!s1.empty()||!s2.empty()||high!=0){
int a=0;
int b=0;
if(s1.empty()){
a=0;
}else{
a=s1.top();s1.pop();
}
if(s2.empty()){
b=0;
}else{
b=s2.top();s2.pop();
}
int low=(a+b+high)%10;
high=(a+b+high)/10;
result.push(low);
}
ListNode* dhead=new ListNode(-1);
ListNode* cur=dhead;
while(!result.empty()){
cur->next=new ListNode(result.top());
cur=cur->next;
result.pop();
}
return dhead->next;
}
};