用栈实现队列
#include <iostream> #include<string> #include<vector> #include<unordered_map> #include <algorithm> #include<map> #include<stack> using namespace std; class MyQueue { public: MyQueue() { } void push(int x) { info_stack.push(x); } int pop() { if (outfo_stack.empty() == 1 && info_stack.empty() == 0) { while (info_stack.empty() == 0) { outfo_stack.push(info_stack.top()); info_stack.pop(); } } if (outfo_stack.empty() == 0) { int result = outfo_stack.top(); outfo_stack.pop(); return result; } else { return NULL; } } int peek() { if (outfo_stack.empty() == 1 && info_stack.empty() == 0) { while (info_stack.empty() == 0) { outfo_stack.push(info_stack.top()); info_stack.pop(); } } if (outfo_stack.empty() == 0) { int result = outfo_stack.top(); return result; } else { return NULL; } } bool empty() { if (info_stack.empty() == 1 && outfo_stack.empty() == 1) return 1; else return 0; } public: stack<int> info_stack; stack<int> outfo_stack; }; int main() { MyQueue obj; obj.push(2); obj.push(3); obj.push(4); cout<<obj.pop()<<endl; obj.push(5); cout << obj.peek() << endl; cout << obj.empty() << endl; cout << obj.pop() << endl; cout << obj.pop() << endl; cout << obj.pop() << endl; cout << obj.empty() << endl; cout << obj.pop() << endl; /*int param_3 = obj.peek(); bool param_4 = obj.empty();*/ return 0; }
二刷
class MyQueue { public: MyQueue() { } void push(int x) { s1.push(x); } int pop() { if(s2.empty() != 1) { int result = s2.top(); s2.pop(); return result; }else { while(s1.empty() != 1) { int tmp = s1.top(); s1.pop(); s2.push(tmp); } int result = s2.top(); s2.pop(); return result; } } int peek() { if(s2.empty() == 1) { while(s1.empty() != 1) { int tmp = s1.top(); s1.pop(); s2.push(tmp); } } return s2.top(); } bool empty() { if(s1.empty() == 1 && s2.empty() == 1) return true; else return false; } public: stack<int> s1,s2; }; /** * Your MyQueue object will be instantiated and called as such: * MyQueue* obj = new MyQueue(); * obj->push(x); * int param_2 = obj->pop(); * int param_3 = obj->peek(); * bool param_4 = obj->empty(); */