原题链接在这里:https://leetcode.com/problems/implement-stack-using-queues/
本题与Implement Queue using Stacks相对应。
Method 1: 用两个queue来实现stack,push(x) 时,x先放到queue2,在把queue1逐个接到queue2上,再把queue1和queue2互换即可。
pop()时直接poll出来queue1的第一个元素即可。
top() 与 pop() 类似。
Note: 1. 首先生成queue时注意要使用LinkedList, 不能用PriorityQueue, 因为PriorityQueue自带排序功能。
2. 刚开始写时用了que2.clear(),看似当时que1是空的,互换写起来多一行,直接clear就行,其实这是错的。因为上一行 que1 = que2按照java来说已经把这两个变量指向同一个object,如果使用que2.clear(),说明que2指向的object被清空了,那么这时que1也指向这个object,que1指向的也是个空的object了,就会出错。所以这里必须使用交替。
AC java:
class MyStack {
private Queue<Integer> que1 = new LinkedList<Integer>();
private Queue<Integer> que2 = new LinkedList<Integer>();
// Push element x onto stack.
public void push(int x) {
que2.offer(x);
while(!que1.isEmpty()){
que2.offer(que1.poll());
}
Queue temp = que1;
que1 = que2;
//que2.clear(); //error
que2 = temp;
}
// Removes the element on top of the stack.
public void pop() {
que1.poll();
}
// Get the top element.
public int top() {
return que1.peek();
}
// Return whether the stack is empty.
public boolean empty() {
return que1.isEmpty();
}
}
Method 2: 这种想法与Method1很类似,不过这次只用一个queue,push(x)时加到队尾,然后rotate size()-1次即可。
AC Java:
<span style="font-size:14px;">class MyStack {
private Queue<Integer> que1 = new LinkedList<Integer>();
// Push element x onto stack.
public void push(int x) {
que1.offer(x);
for(int i = 0; i<que1.size()-1;i++){
que1.offer(que1.poll());
}
}
// Removes the element on top of the stack.
public void pop() {
que1.poll();
}
// Get the top element.
public int top() {
return que1.peek();
}
// Return whether the stack is empty.
public boolean empty() {
return que1.isEmpty();
}
}</span>