使用栈实现队列的下列操作:
push(x) -- 将一个元素放入队列的尾部
pop() -- 从队列首部移除元素
peek() -- 返回队列首部的元素
empty() -- 返回队列是否为空。
我个人的思路:我觉得push()这个函数设计好了,就可以解决其他的函数。
方法一:使用两个栈stack1和stack2,这两个栈颠来颠去,可以实现。
class MyQueue1 {
Stack<Integer> stack1;
Stack<Integer> stack2;
public MyQueue1() {
stack1 = new Stack<>();
stack2 = new Stack<>();
}
public void push(int x) {
while (!stack1.isEmpty()) {
stack2.add(stack1.pop());
}
stack1.add(x);
while (!stack2.isEmpty()) {
stack1.add(stack2.pop());
}
}
public int pop() {
return stack1.pop();
}
public int peek() {
return stack1.peek();
}
public boolean empty() {
return stack1.isEmpty();
}
}
方法二:一个栈实现,不过借助了动态数组
class MyQueue {
Stack<Integer> stack;
public MyQueue() {
stack = new Stack<>();
}
public void push(int x) {
ArrayList<Integer> list = new ArrayList<>();
while (!stack.isEmpty()) {
list.add(stack.pop());
}
stack.add(x);
if (list.size() > 0) {
for (int i = list.size() - 1; i >= 0; i--) {
stack.add(list.get(i));
}
}
}
//部分省略
}
end.