Implement the following operations of a queue using stacks.
- push(x) – Push element x to the back of queue.
- pop() – Removes the element from in front of queue.
- peek() – Get the front element.
- empty() – Return whether the queue is empty.
Notes:
- You must use only standard operations of a stack – which means only
push to top, peek/pop from top, size, and is empty operations are
valid. - Depending on your language, stack may not be supported natively. You
may simulate a stack by using a list or deque (double-ended queue),
as long as you use only standard operations of a stack. - You may assume that all operations are valid (for example, no pop or
peek operations will be called on an empty queue).
使用栈来实现一个队列。这个题目之前在《剑指offer》上面见过,没有什么好说的。使用两个栈,一个栈用来保存插入的元素。另外一个栈用来运行pop或top操作,每当运行pop或top操作时检查另外一个栈是否为空,假设为空,将第一栈中的元素所有弹出并插入到第二个栈中。再将第二个栈中的元素弹出就可以。须要注意的是这道题的编程时有一个技巧,能够使用peek来实现pop。这样能够降低反复代码。编程时要能扩展思维,假设因为pop函数的声明再前面就陷入用pop来实现peek的功能的话就会感觉无从下手了。
runtime:0ms
class Queue {
public:
// Push element x to the back of queue.
void push(int x) {
pushStack.push(x);
}
// Removes the element from in front of queue.
void pop(void) {
peek();//这里能够使用peek进行两个栈之间元素的转移从而避免反复代码
popStack.pop();
}
// Get the front element.
int peek(void) {
if(popStack.empty())
{
while(!pushStack.empty())
{
popStack.push(pushStack.top());
pushStack.pop();
}
}
return popStack.top();
}
// Return whether the queue is empty.
bool empty(void) {
return pushStack.empty()&&popStack.empty();
}
private:
stack<int> pushStack;//数据被插入到这个栈中
stack<int> popStack;//数据从这个栈中弹出
};