- 栈:先进后出,队列先进先出。关键就是:两个栈实现队列,一个栈用来进,一个栈用来出
class MyQueue {
public:
stack<int> stackin;
stack<int> stackout;
MyQueue() {
}
void push(int x) {
stackin.push(x);//push,not push_back
}
int pop() {//pop的思想,out栈空的时候,往进放
if(stackout.empty()){//stackout 为空
while(!stackin.empty()){
int a=stackin.top();
stackout.push(a);
stackin.pop();
}
}
int ans=stackout.top();
stackout.pop();
return ans;
}
int peek() {//peek直接调用自身的pop函数
int ans=this->pop();
stackout.push(ans);
return ans;
}
bool empty() {
return stackin.empty()&&stackout.empty();
}
};
/**
* 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();
*/
- 用一个队列就可以实现栈,搞清楚队列的常用函数弹出的是哪些元素,而栈应该弹出哪些元素
- 关键:123(1先进),如果是队列,那么1先出,如果是栈,那么3先出。所以让3前面的元素重新在压进来,然后让3出就可以了
class MyStack {
public:
queue<int> que;
MyStack() {
}
void push(int x) {
que.push(x);
}
int pop() {//主要的思想就是最后一个元素之前的重新压入队列中
int size=que.size();
size--;
while(size--){
que.push(que.front());
que.pop();
}
int ans=que.front();
que.pop();
return ans;
}
int top() {
int ans=que.back();
return ans;
}
bool empty() {
return que.empty();
}
};
/**
* 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();
*/