【题目描述】
【思路】
根据两种数据结构的特点,队列:先进先出 。栈:先进后出。
因此想到使用两个栈,一个作为数据栈,另一个用于中转。当进行队列的peek和pop操作时,只要通过中转栈使得原先数据栈中的栈底元素变为中转栈的栈顶元素,就使得中转栈的peek、pop操作与队列一致。
class MyQueue {
/*
思路是当进行队列的peek和pop操作时,要使得原先数据栈中的栈底元素变为栈顶元素
*/
Stack<Integer> stack = new Stack<Integer>(); //数据栈
Stack<Integer> stack2 = new Stack<Integer>(); //中转栈 做弹出 和取栈顶用
/** Initialize your data structure here. */
public MyQueue() {
}
/** Push element x to the back of queue. */
public void push(int x) {
stack.push(x);
}
/** Removes the element from in front of queue and returns that element. */
//题目说了:在队列为空时,不会进行pop或者peek等操作;
public int pop() {
//将stack中的元素自栈顶push到stack2中
while( !stack.empty() ){
//将stack的栈顶元素移动到stack2栈底 相当于移动到队尾
stack2.push( stack.pop() );
}
int value = stack2.pop();
//再将剩余元素重新push回stack
while( !stack2.empty()){
stack.push( stack2.pop());
}
return value;
}
/** Get the front element. */
public int peek() {
//将stack中的元素push到stack2中
while( !stack.empty() ){
//将stack的栈顶元素移动到stack2栈底 相当于队尾
stack2.push( stack.pop() );
}
int value = stack2.peek();
//再将剩余元素重新push会stack
while( !stack2.empty()){
stack.push( stack2.pop());
}
return value;
}
/** Returns whether the queue is empty. */
public boolean empty() {
return stack.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();
* boolean param_4 = obj.empty();
*/