赞
踩
使用栈实现队列的下列操作:
示例:
MyQueue queue = new MyQueue();
queue.push(1);
queue.push(2);
queue.peek(); // 返回 1
queue.pop(); // 返回 1
queue.empty(); // 返回 false
说明:
public class Ex232<T> {
public Stack<Integer> stack;
public Stack<Integer> curStack;
public Ex232(){
stack = new Stack<>();
curStack = new Stack<>();
}
/** 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. */
public int pop() {
peek();
return curStack.pop();
}
/** Get the front element. */
public int peek() {
if (curStack.isEmpty()) {
while (!stack.isEmpty()) {
curStack.push(stack.pop());
}
}
return curStack.peek();
}
/** Returns whether the queue is empty. */
public boolean empty() {
return stack.isEmpty()&&curStack.isEmpty();
}
public static void main(String[] args) {
Ex232 queue = new Ex232();
queue.push(1);
queue.push(2);
queue.push(3);
queue.push(5);
// queue.peek(); // 返回 1
System.out.println(queue.peek());
// queue.pop(); // 返回 1
System.out.println(queue.pop());
queue.empty();
}
}
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。