题9:
用两个队列表示栈
用两个栈表示队列
两个队列表示栈:
- 准备两个队列queue和help
- 进栈操作:将所有的值放入queue队列
- 出栈操作:
- 将queue队列最后一个数之前的数取出放到help队列中
- 取出最后一个数对外返回
- 交换两个队列的指针引用
public class QueueToStack{
//用两个队列表示栈
private Queue<Integer> queue;
private Queue<Integer> help;
public TwoQueueToStack(){
queue = new LinkedList<Integer>();
help = new LinkedList<Integer>();
}
//进栈
public void push(int pushInt){
queue.add(pushInt);
}
//出栈 把queue最后一个数之前的数pop到help队列里 把queue队列的最后一个数pop出返回,交换两个队列的引用
public int poll(){
if(queue.isEmpty()){
throw new RuntimeException("The Stack Is Empty!");
}
while(queue.size() > 1){
help.add(queue.poll());
}
int res = queue.poll();
swap();
return res;
}
//取得栈顶的元素
public int peek(){
if(queue.isEmpty()){
throw new RuntimeException("The Stack Is Empty!");
}
while(queue.size() != 1){
help.add(queue.poll());
}
int res = queue.peek();
help.add(queue.poll());
swap();
return res;
}
//交换两个队列的引用
private void swap(){
Queue<Integer> tem = help;
help = queue;
queue = tem;
}
}
两个栈表示队列:
- 准备两个队列,push和pop
- 进队操作:将进入队列的数放进push栈
- 出队操作:
- 直接从pop栈中取出元素返回
- 把pop栈中的元素取完后,把push栈中的所有元素取出放到pop栈中
public class StackToQueue{
//用两个栈表示队列
private Stack<Integer> stackPush;
private Stack<Integer> stackPop;
//初始化
public StackToQueue(){
stackPush = new Stack<Integer>();
stackPop = new Stack<Integer>();
}
//进队列
public void push(int pushInt){
stackPush.push(pushInt);
}
//出队列 直接从stackPop栈里pop出元素返回
//stackPop栈的元素pop完后,再把stackPush栈里的所有元素pop到stackPop栈
public int poll(){
if(stackPop.empty() && stackPush.empty()){
throw new RuntimeException("The Queue Is Empty!");
} else if(stackPop.empty()){
while(!stackPush.empty()){
stackPop.push(stackPush.pop());
}
}
return stackPop.pop();
}
//取得队列头的元素
public int peek(){
if(stackPop.empty() && stackPush.empty()) {
throw new RuntimeException("The Queue Is Empty!");
} else if(stackPop.empty()){
while(!stackPush.empty()){
stackPop.add(stackPush.pop());
}
}
return stackPop.peek();
}
}