使用队列实现栈的下列操作:
push(x) – 元素 x 入栈
pop() – 移除栈顶元素
top() – 获取栈顶元素
empty() – 返回栈是否为空
注意:
你只能使用队列的基本操作-- 也就是 push to back, peek/pop from front, size, 和 is empty 这些操作是合法的。
你所使用的语言也许不支持队列。 你可以使用 list 或者 deque(双端队列)来模拟一个队列 , 只要是标准的队列操作即可。
你可以假设所有操作都是有效的(例如, 对一个空的栈不会调用 pop 或者 top 操作)
思路:利用两个队列来进行调换
例如:将1 2 3 4 5 依次进入栈中得到的结果是
现要用队列实现栈的存储,则希望队列的存储形式为:
则考虑用两个队列实现:
1.定义一个临时队列temp_queue
2.定义一个最终存储的链表final_queue
第一步:1 -->temp_queue
while(!final_queue.isEmpty()) {
temp_queue.add(final_queue.peek());
final_queue.poll();
}
while(!temp_queue.isEmpty()){
final_queue.add(temp_queue.peek());
temp_queue.poll();
}
第二步:2–>temp_queue
while(!final_queue.isEmpty()) {
temp_queue.add(final_queue.peek());
final_queue.poll();
}
while(!temp_queue.isEmpty()){
final_queue.add(temp_queue.peek());
temp_queue.poll();
}
第三步:3–>temp_queue
while(!final_queue.isEmpty()) {
temp_queue.add(final_queue.peek());
final_queue.poll();
}
while(!temp_queue.isEmpty()){
final_queue.add(temp_queue.peek());
temp_queue.poll();
}
以此类推,将最终结果存储在final_queue中
完整代码如下:
class MyStack {
Queue<Integer> final_queue;//最终队列
Queue<Integer> temp_queue;//临时队列
//思路:用一个临时队列来存储
/** Initialize your data structure here. */
public MyStack() {
final_queue = new LinkedList<>();
temp_queue = new LinkedList<>();
}
/** Push element x onto stack. */
public void push(int x) {
temp_queue.add(x);
while(!final_queue.isEmpty()) {
temp_queue.add(final_queue.peek());
final_queue.poll();
}
while(!temp_queue.isEmpty()){
final_queue.add(temp_queue.peek());
temp_queue.poll();
}
}
/** Removes the element on top of the stack and returns that element. */
public int pop() {
return final_queue.poll();
}
/** Get the top element. */
public int top() {
return final_queue.peek();
}
/** Returns whether the stack is empty. */
public boolean empty() {
return final_queue.isEmpty();
}
}
如有疑问,请留言。