class Solution { public: ListNode* addInList(ListNode* head1, ListNode* head2) { if (head1 == nullptr) return head2; if (head2 == nullptr) return head1; stack<unsigned char> v1; stack<unsigned char> v2; stack<unsigned char> ret; for (auto cur = head1; cur != nullptr;) { v1.push(cur->val); auto next_node = cur->next; delete cur; cur = next_node; } for (auto cur = head2; cur != nullptr;) { v2.push(cur->val); auto next_node = cur->next; delete cur; cur = next_node; } bool carry = false; while (!(v1.empty() && v2.empty())) { unsigned char a; unsigned char b; if (v1.empty()) a = 0; else { a = v1.top(); v1.pop(); } if (v2.empty()) b = 0; else { b = v2.top(); v2.pop(); } auto cur_num = a + b + (unsigned char)carry; if (cur_num >= 10) { carry = true; cur_num -= 10; } else carry = false; ret.push(cur_num); } if (carry) ret.push(1); ListNode* output = nullptr; auto cur = &output; while (!ret.empty()) { *cur = new ListNode(ret.top()); ret.pop(); cur = &((*cur)->next); } return output; } };
模拟即可,没什么难度。
整活:O(-1)空间复杂度暴杀,用unsigned char存储数字并且把原本的链表删除,理论上可以实现比输入还低的内存占用。这个代码占用内存大约20000KB(发布之日的运行环境),稳定击败100%答案。