本次两道题偏向于对栈和队列机制的学习,具体底层机制可以
看此学习。
232.用栈实现队列
class MyQueue {
public:
stack<int> in;
stack<int> out;
MyQueue() {
}
void push(int x) {
in.push(x);
}
int pop() {
if (out.empty()){
while (!in.empty()){
out.push(in.top());
in.pop();
}
}
int ans = out.top();
out.pop();
return ans;
}
int peek() {
int ans = this->pop();//调用pop函数,this指针指向成员函数作用对象
out.push(ans);//因为只返回,不删除,所以需要添加回去
return ans;
}
bool empty() {
return in.empty() && out.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();
*/
225. 用队列实现栈
class MyStack {
public:
queue<int> in;
MyStack() {
}
void push(int x) {
in.push(x);
}
int pop() {
int n = in.size();
for (int i = 0; i < n-1; i++){
in.push(in.front());
in.pop();
}
int ans = in.front();
in.pop();
return ans;
}
int top() {
return in.back();
}
bool empty() {
return in.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();
*/