|
发表于 2022-3-29 23:03:01
|
显示全部楼层
- #include <stack>
- #include <cstddef>
- //#define DEBUG
- #ifdef DEBUG
- #include <iostream>
- using std::cout, std::endl;
- #endif
- using std::stack;
- template<typename T>
- class queue {
- public:
- void push(const T &value) {
- this->lhs.push(value);
- }
- void pop() {
- this->move(this->lhs, this->rhs);
- this->rhs.pop();
- this->move(this->rhs, this->lhs);
- }
- const T top() {
- this->move(this->lhs, this->rhs);
- const T result = this->rhs.top();
- this->move(this->rhs, this->lhs);
- return result;
- }
- bool empty() {
- return this->lhs.empty();
- }
- private:
- stack<T> lhs, rhs;
- // lhs to rhs
- static void move(stack<T> &lhs, stack<T> &rhs) {
- while(!lhs.empty()) {
- rhs.push(lhs.top());
- lhs.pop();
- }
- }
- };
- int main() {
- #ifdef DEBUG
- {
- queue<size_t> q;
- q.push(1);
- q.push(2);
- q.push(3);
- cout << q.top() << endl;
- q.pop();
- q.push(4);
- while(!q.empty()) {
- cout << q.top() << endl;
- q.pop();
- }
- return 0;
- }
- #endif
- queue<size_t> q;
- q.push(1);
- q.push(2);
- q.push(3);
- q.pop();
- q.push(4);
- while(!q.empty()) q.pop();
- return 0;
- }
复制代码 |
|