题目
:请你仅使用两个队列实现一个后入先出(LIFO)的栈,并支持普通栈的全部四种操作(push、top、pop 和 empty)。
实现 MyStack 类:
void push(int x) 将元素 x 压入栈顶。
int pop() 移除并返回栈顶元素。
int top() 返回栈顶元素。
boolean empty() 如果栈是空的,返回 true ;否则,返回 false 。
题解
:这是一道模拟题,不涉及到具体算法,考察的就是对栈和队列的掌握程度。使用栈来模拟队列的行为,如果仅仅用一个栈,是一定不行的,所以需要两个栈一个输入栈,一个输出栈,要注意输入栈和输出栈的关系。
代码(C++)
:
class MyQueue {
public:
stack<int> stIn;
stack<int> stOut;
MyQueue() {
}
void push(int x) {
stIn.push(x);
}
int pop() {
int cur,res;
while(!stIn.empty()){
cur = stIn.top();
stIn.pop();
stOut.push(cur);
}
res = stOut.top();
stOut.pop();
while(!stOut.empty()){
cur = stOut.top();
stOut.pop();
stIn.push(cur);
}
return res;
}
int peek() {
int cur,res;
while(!stIn.empty()){
cur = stIn.top();
stIn.pop();
stOut.push(cur);
}
res = stOut.top();
while(!stOut.empty()){
cur = stOut.top();
stOut.pop();
stIn.push(cur);
}
return res;
}
bool empty() {
return stIn.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();
*/
写在后面
这个专栏主要是我在刷题的过程中总结的一些笔记,因为我学的也很一般,如果有错误和不足之处,还望大家在评论区指出。希望能给大家的学习带来一点帮助,共同进步!!!