题目:
使用两个队列实现一个栈,完成其pop,push,peek等功能。
分析:
一个队列用作push;
一个队列用作help;
两个队列在peek或pop后可以相互转换
代码实现:
import java.util.LinkedList;
import java.util.Queue;
public class TwoQueueStack {
private Queue<Integer> queue;
private Queue<Integer> help;
public TwoQueueStack() {
queue = new LinkedList<>();
help = new LinkedList<>();
}
public void push(int newNum) {
queue.push(newNum);
}
public int peek() {
if(queue.isEmpty()) {
throw new RuntimeException("stack is empty.");
}
while(queue.size()!=1) {
help.add(queue.poll());
}
int res = queue.poll();
help.add(queue.poll()); // pop与peek唯一区别的地方
swap(); // 此函数用来交换queue与help,此处与两个栈实现队列来说,比较方便的一点
return res;
}
public int pop() {
if(queue.isEmpty()) {
throw new RuntimeException("stack is empty.");
}
while(queue.size()!=1) {
help.add(queue.poll());
}
int res = queue.poll();
swap();
return res;
}
public void swap() {
Queue<Integer> tmp = help;
help = queue;
queue = tmp;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
}
}