用栈先存着两个node的东西,再pop出来相加。
转载请注明: http://blog.csdn.net/c602273091/article/details/54317115
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
int cf = 0;
stack<int> q_1;
stack<int> q_2;
while(l1 != NULL || l2 != NULL)
{
if(l1 != NULL)
{
q_1.push(l1->val);
l1 = l1->next;
}
if(l2 != NULL)
{
q_2.push(l2->val);
l2 = l2->next;
}
}
ListNode *rel = NULL;
while(!q_1.empty() && !q_2.empty())
{
int a1 = q_1.top(), a2 = q_2.top();
cout << a1 << " " << a2 << endl;
int sum_tmp = q_1.top() + q_2.top() + cf;
q_1.pop();
q_2.pop();
cf = sum_tmp/10;
sum_tmp = sum_tmp%10;
ListNode *tmp = new ListNode(sum_tmp);
tmp->next = rel;
rel = tmp;
}
while(!q_1.empty())
{
int tmp_q_1 = q_1.top() + cf;
q_1.pop();
cf = tmp_q_1/10;
tmp_q_1 = tmp_q_1 % 10;
ListNode *tmp2 = new ListNode(tmp_q_1);
tmp2->next = rel;
rel = tmp2;
}
while(!q_2.empty())
{
int tmp3 = q_2.top() + cf;
q_2.pop();
cf = tmp3/10;
tmp3 = tmp3 % 10;
ListNode *tmp2 = new ListNode(tmp3);
tmp2->next = rel;
rel = tmp2;
}
if(cf)
{
ListNode *tmp = new ListNode(cf);
tmp->next = rel;
rel = tmp;
}
/*
while(rel != NULL)
{
cout << rel->val << endl;
rel = rel->next;
}*/
return rel;
}
};