使用棧實現隊列的下列操作:
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)