使用栈实现队列的下列操作:
push(x) – 将一个元素放入队列的尾部。
pop() – 从队列首部移除元素。
peek() – 返回队列首部的元素。
empty() – 返回队列是否为空。
方法1:辅助栈
思路:
用栈模拟队列的关键是保证新元素位于栈底(即让新元素排在队尾)。
设有栈s1,s2,s1为数据栈,s2为辅助栈。新元素来得时候,将s1中的元素倒入s2,再将新元素入栈s1,最后再从s2中将元素放回s1,实现新元素排在队尾的目的。
import java.util.Queue;
import java.util.Stack;
//leetcode submit region begin(Prohibit modification and deletion)
class MyQueue {
Stack<Integer> stack1;
Stack<Integer> stack2;
/** Initialize your data structure here. */
public MyQueue() {
stack1 = new Stack<>(); // 数据栈
stack2 = new Stack<>(); // 辅助栈
}
/** Push element x to the back of queue. */
public void push(int x) {
while (!stack1.isEmpty()){ // s1中数据转入s2
int temp = stack1.pop();
stack2.push(temp);
}
stack1.push(x); // s1中入栈新元素
while (!stack2.isEmpty()){ // 将s2中的元素放回s1
int temp = stack2.pop();
stack1.push(temp);
}
}
/** Removes the element from in front of queue and returns that element. */
public int pop() {
return stack1.pop();
}
/** Get the front element. */
public int peek() {
return stack1.peek();
}
/** Returns whether the queue is empty. */
public boolean empty() {
return stack1.isEmpty();
}
}
/**
* 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();
*/
//leetcode submit region end(Prohibit modification and deletion)
方法2:辅助栈
思路:
通过将s1中的数据倒入s2,实现s1中数据顺序的逆转,从而使得s1中的栈底元素成为s2的栈顶元素。当s2非空时,出队操作即为s2的出栈操作;当s2为空时,将s1的数据倒入s2,再对s2进行出栈操作。
import java.util.Queue;
import java.util.Stack;
//leetcode submit region begin(Prohibit modification and deletion)
class MyQueue {
Stack<Integer> stack1;
Stack<Integer> stack2;
int front; // 保存s1的栈底元素
/** Initialize your data structure here. */
public MyQueue() {
stack1 = new Stack<>(); // 数据栈
stack2 = new Stack<>(); // 辅助栈
}
/** Push element x to the back of queue. */
public void push(int x) {
if (stack1.isEmpty()){
front = x; // 防止s2为空时,丢失队首元素
}
stack1.push(x);
}
/** Removes the element from in front of queue and returns that element. */
public int pop() {
if (stack2.isEmpty()){
while (!stack1.isEmpty()){
stack2.push(stack1.pop());
}
}
return stack2.pop();
}
/** Get the front element. */
public int peek() {
if (stack2.isEmpty()){
return front;
}
return stack2.peek();
}
/** Returns whether the queue is empty. */
public boolean empty() {
return stack1.isEmpty()&& stack2.isEmpty();
}
}
/**
* 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();
*/
//leetcode submit region end(Prohibit modification and deletion)