用列队实现栈
两个队列实现栈
#include <iostream> #include<string> #include<vector> #include<unordered_map> #include <algorithm> #include<map> #include<stack> #include <queue> using namespace std; class MyStack { public: MyStack() { } void push(int x) { que_1.push(x); } int pop() { int result = 0; while (que_1.empty() == 0) { result = que_1.front(); que_2.push(que_1.front()); que_1.pop(); } int num = que_2.size() - 1; for (int i = 0; i < num ; i++) { que_1.push(que_2.front()); que_2.pop(); } que_2.pop(); return result; } int top() { int result = 0; while (que_1.empty() == 0) { result = que_1.front(); que_2.push(que_1.front()); que_1.pop(); } while (que_2.empty() == 0) { que_1.push(que_2.front()); que_2.pop(); } return result; } bool empty() { if (que_1.empty() == 1)return 1; else return 0; } public: queue<int> que_1; queue<int> que_2; }; int main() { MyStack obj; obj.push(1); obj.push(2); obj.push(3); cout << obj.pop() << endl; cout << obj.pop() << endl; cout << obj.pop() << endl; cout << obj.empty() << endl; return 0; }
一个队列实现栈
class MyStack { public: MyStack() { } void push(int x) { que_1.push(x); } int pop() { int result = 0; int size = que_1.size() -1 ; for (int i = 0; i < size; i++) { result = que_1.front(); que_1.pop(); que_1.push(result); } result = que_1.front(); que_1.pop(); return result; } int top() { int result = 0; int size = que_1.size() ; for (int i = 0; i < size; i++) { result = que_1.front(); que_1.pop(); que_1.push(result); } return result; } bool empty() { if (que_1.empty() == 1)return 1; else return 0; } public: queue<int> que_1; };
二刷
一个队列实现
class MyStack { public: MyStack() { } void push(int x) { q1.push(x); } int pop() { int num = q1.size()-1; while(num--) { int tmp = q1.front(); q1.pop(); q1.push(tmp); } int result = q1.front(); q1.pop(); return result; } int top() { return q1.back(); } bool empty() { return q1.empty(); } public: queue<int> q1; }; /** * Your MyStack object will be instantiated and called as such: * MyStack* obj = new MyStack(); * obj->push(x); * int param_2 = obj->pop(); * int param_3 = obj->top(); * bool param_4 = obj->empty(); */