题解 | #链表相加(二)#
链表相加(二)
http://www.nowcoder.com/practice/c56f6c70fb3f4849bc56e33ff2a50b6b
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
// 利用栈来做,代码好长啊,和其他人题解不太一样,发出来看看^^ ^^ ^_^
class Solution {
public:
/**
*
* @param head1 ListNode类
* @param head2 ListNode类
* @return ListNode类
*/
ListNode* addInList(ListNode* head1, ListNode* head2) {
// write code here
stack<ListNode*> arr1, arr2;
if(!head1) return head1;
if(!head2) return head2;
ListNode *p1 = head1, *p2 = head2;
while(p1)
{
arr1.push(p1);
p1 = p1->next;
}
while(p2)
{
arr2.push(p2);
p2 = p2->next;
}
int flag = 0;
int sum = 0;
ListNode *l = nullptr, *r = nullptr;
while(arr1.size() && arr2.size())
{
p1 = arr1.top();
arr1.pop();
p2 = arr2.top();
arr2.pop();
sum = p1->val + p2->val + flag;
flag = sum / 10;
sum = sum % 10;
l = new ListNode(sum);
l->next = r;
r = l;
}
while(arr1.size())
{
p1 = arr1.top();
arr1.pop();
sum = p1->val + flag;
flag = sum / 10;
sum = sum % 10;
l = new ListNode(sum);
l->next = r;
r = l;
}
while(arr2.size())
{
p2 = arr2.top();
arr2.pop();
sum = p2->val + flag;
flag = sum / 10;
sum = sum % 10;
l = new ListNode(sum);
l->next = r;
r = l;
}
if(flag != 0)
{
l = new ListNode(flag);
l->next = r;
r = l;
}
return l;
}
};