-
使用栈实现队列的下列操作:
push(x) – 将一个元素放入队列的尾部。
pop() – 从队列首部移除元素。
peek() – 返回队列首部的元素。
empty() – 返回队列是否为空。
示例:MyQueue queue = new MyQueue();
queue.push(1);
queue.push(2);
queue.peek(); // 返回 1
queue.pop(); // 返回 1
queue.empty(); // 返回 false
class MyQueue {
private Stack<Integer> temp_sk;
private Stack<Integer> final_sk;
public MyQueue() {
temp_sk = new Stack<>();
final_sk = new Stack<>();
}
public void push(int x) {
while(!temp_sk.isEmpty()) {
final_sk.push(temp_sk.peek());
temp_sk.pop();
}
temp_sk.push(x);
while(!final_sk.isEmpty()) {
temp_sk.push(final_sk.peek());
final_sk.pop();
}
}
public int pop() {
return temp_sk.pop();
}
public int peek() {
return temp_sk.peek();
}
public boolean empty() {
return temp_sk.isEmpty() ;
}
}
执行用时 :0 ms, 在所有 Java 提交中击败了100.00%的用户
内存消耗 :40.8 MB, 在所有 Java 提交中击败了5.12%的用户