题意:将两个以链表形式存储的数字向加,并以链表形式输出。
思路:先按位向加,最后将链表颠倒。
/**
* 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;
}
};

本文介绍了一种链表数字相加的算法实现,通过使用栈来存储链表中的每个数字,然后逐位进行相加并处理进位,最终得到结果链表。此方法适用于需要对大数进行操作的场景。
254

被折叠的 条评论
为什么被折叠?



