C++标准里面对于栈,总共就给出了四种操作:入栈push,出栈pop,检查是否为空empty,返回栈的顶top。
本题考查用栈的四种操作组合来实现队列queue的操作,可谓考查数据结构的基本功。解决方法之一是,使用两个栈,一个负责“进”,另一个负责“出”。
难点是队列的出队操作,也就是pop,当负责“”的栈是空的时候同时负责进的栈非空,则此时先将负责“进”的栈的所有元素依次全部pop出来再依次全部push进负责“出”的栈中。这样再执行负责“出”的栈的pop操作。
C++代码如下:
class Queue {
public:
stack<int> stk1;
stack<int> stk2;
// Push element x to the back of queue.
void push(int x) {
stk1.push(x);
}
// Removes the element from in front of queue.
void pop(void) {
if(stk2.empty()){
while(!stk1.empty()){
int top = stk1.top();
stk1.pop();
stk2.push(top);
}
}
stk2.pop();
}
// Get the front element.
int peek(void) {
if(stk2.empty()){
while(!stk1.empty()){
int top = stk1.top();
stk1.pop();
stk2.push(top);
}
}
return stk2.top();
}
// Return whether the queue is empty.
bool empty(void) {
return stk1.empty()&&stk2.empty();
}
};
java代码如下:
class MyQueue {
Stack<Integer> stk1 = new Stack();
Stack<Integer> stk2 = new Stack();
// Push element x to the back of queue.
public void push(int x) {
stk1.push(x);
}
// Removes the element from in front of queue.
public void pop() {
peek();
stk2.pop();
}
// Get the front element.
public int peek() {
if(stk2.empty()){
while(!stk1.empty()){
stk2.push(stk1.pop());
}
}
return stk2.peek();
}
// Return whether the queue is empty.
public boolean empty() {
return stk1.empty()&&stk2.empty();
}
}