题目地址:
https://www.lintcode.com/problem/implement-stack-by-two-queues/description
用两个队列来实现栈。
开两个队列和,其中作辅助用。push的时候直接向里添加即可。pop和top的时候,要先将中除了最后一个元素以外的元素都poll出来并加入,然后取出仅剩的那个元素,再将两个队列引用交换。如果是pop的话,交换前要将的那个元素也poll出来,如果是top的话,交换前要将那个元素进。代码如下:
import java.util.ArrayDeque;
import java.util.Queue;
public class Stack {
Queue<Integer> q1 = new ArrayDeque<>(), q2 = new ArrayDeque<>();
/*
* @param x: An integer
* @return: nothing
*/
public void push(int x) {
// write your code here
q1.offer(x);
}
/*
* @return: nothing
*/
public void pop() {
// write your code here
while (q1.size() > 1) {
q2.offer(q1.poll());
}
q1.poll();
Queue<Integer> tmp = q1;
q1 = q2;
q2 = tmp;
}
/*
* @return: An integer
*/
public int top() {
// write your code here
while (q1.size() > 1) {
q2.offer(q1.poll());
}
int res = q1.peek();
q2.offer(q1.poll());
Queue<Integer> tmp = q1;
q1 = q2;
q2 = tmp;
return res;
}
/*
* @return: True if the stack is empty
*/
public boolean isEmpty() {
// write your code here
return q1.isEmpty();
}
}
push时间复杂度,pop和top时间复杂度,为已经在队列里的元素个数。空间。