题目:
实现一个MyQueue类,该类用两个栈来实现一个队列。
实例:
MyQueue queue = new MyQueue();
queue.push(1);
queue.push(2);
queue.peek();// 返回 1
queue.pop();// 返回 1
queue.empty(); // 返回 false
说明:
你只能使用标准的栈操作 — 也就是只有 push to top, peek/pop from top, size 和 is empty 操作是合法的。你所使用的语言也许不支持栈。你可以使用 list 或者 deque(双端队列)来模拟一个栈,只要是标准的栈操作即可。假设所有操作都是有效的 (例如,一个空的队列不会调用 pop 或者 peek 操作)。
Related Topics
栈 设计 队列
思路:
栈是先进后出的类型,这里实现是使用java.util.Stack类。用2个栈进行相互调换数据,来达到先进先出的效果。每次插入的时候将所有数据放入第一个栈中,读数据、删除数据将所有数据放入第二个栈中栈中,然后针对对应栈栈进行操作即可。(其中需要遍历某一个栈的数据到另一个栈中,实现队列的效果)
代码:
class MyQueue {
Stack<Integer> stack1, 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 (!stack2.empty()) {
stack1.push(stack2.pop());
}
stack1.push(x);
}
/**
* Removes the element from in front of queue and returns that element.
*/
public int pop() {
//交换栈
while (!stack1.empty()) {
stack2.push(stack1.pop());
}
return stack2.pop();
}
/**
* Get the front element.
*/
public int peek() {
//交换栈
while (!stack1.empty()) {
stack2.push(stack1.pop());
}
return stack2.peek();
}
/**
* Returns whether the queue is empty.
*/
public boolean empty() {
//查看两个栈中是否有数据。
return stack1.empty() && stack2.empty();
}
}