class MyQueue {
public:
/** Initialize your data structure here. */
//用两个栈实现队列。时间复杂度o(n);
//push操作就是在主栈上push
//pop操作就是先将主栈元素输入到副栈里,然后弹出栈顶元素,再Pop;
//peek 操作相对于pop操作少一个pop操作即可,弹出副栈栈顶即可。
//empty 就是判断主栈是否为空。
stack<int>sta,c;
MyQueue() {
}
/** Push element x to the back of queue. */
void push(int x) {
sta.push(x);
}
/** Removes the element from in front of queue and returns that element. */
int pop() {
while(!sta.empty()) c.push(sta.top()),sta.pop();
int x=c.top();
c.pop();
while(!c.empty()) sta.push(c.top()),c.pop();
return x;
}
/** Get the front element. */
int peek() {
while(!sta.empty()) c.push(sta.top()),sta.pop();
int x=c.top();
while(!c.empty()) sta.push(c.top()),c.pop();
return x;
}
/** Returns whether the queue is empty. */
bool empty() {
return sta.empty();
}
};
/**
* Your MyQueue object will be instantiated and called as such:
* MyQueue obj = MyQueue();
* obj.push(x);
* int param_2 = obj.pop();
* int param_3 = obj.peek();
* bool param_4 = obj.empty();
*/
剑指offer 20.用两个栈实现队列
最新推荐文章于 2024-05-20 20:08:58 发布