您的位置:首页 > 其它

Leetcode Add Two Numbers II

2017-01-01 08:43 453 查看
题意:将两个以链表形式存储的数字向加,并以链表形式输出。

思路:先按位向加,最后将链表颠倒。

/**
* 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) {
stack<int> sl1;
stack<int> sl2;
ListNode* next = l1;
while(next) {
sl1.push(next->val);
next = next->next;
}
next = l2;
while(next) {
sl2.push(next->val);
next = next->next;
}
ListNode* myhead = new ListNode(0);
next = myhead;
int c = 0;
while(!sl1.empty() || !sl2.empty()) {
int a = 0;
int b = 0;
if(!sl1.empty()) {
a = sl1.top();
sl1.pop();
}
if(!sl2.empty()) {
b = sl2.top();
sl2.pop();
}

ListNode* temp = new ListNode((a + b + c) % 10);
c = (a + b + c) / 10;
next->next = temp;
next = temp;
}

if(c) {
ListNode* temp = new ListNode(c);
next->next = temp;
next = temp;
}

//show the result

// reverse
next = myhead->next;
ListNode* pre = NULL;
while(next) { cout << next->val << endl;
ListNode* temp = next->next;
next->next = pre;
pre = next;
next = temp;

}

return pre;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  leetcode 链表