232. 用栈实现队列
第一想法
队列是先进先出,栈是先进后出,STL底层本质都是用deque做底层封装,把一些接口封住。其实这里要注意的就是,pop()
需要把输入栈移动到输出栈,如果输出栈本身就有数字,说明top()
已经是队头的数字。
代码
class MyQueue {
public:
stack<int> a;
stack<int> b;
MyQueue() {
}
void push(int x) {
a.push(x);
}
int pop() {
if (b.empty()){
while(!a.empty()){
b.push(a.top());
a.pop();
}
}
auto res = b.top();
b.pop();
return res;
}
int peek() {
auto res = pop();
b.push(res);
return res;
}
bool empty() {
return a.empty()&&b.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> q;
MyStack() {
}
void push(int x) {
q.push(x);
}
int pop() {
int size = q.size() - 1;
while (size --){
auto a = q.front();
q.push(a);
q.pop();
}
auto res = q.front();
q.pop();
return res;
}
int top() {
auto res = pop();
q.push(res);
return res;
}
bool empty() {
return q.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();
*/