1、题目描述
用两个栈来实现一个队列,完成队列的 Push 和 Pop 操作。 队列中的 元素为 int 类型。
2、题目分析
由于队列是先进先出的,而栈是先进后出的,故可以用2个栈实现队列的入、出队功能,队列的入队功能与栈的一样,出队时,先将第一个栈中的元素全部弹出,并倒入到第二个栈中,将第二个栈中栈顶元素弹出,并将stack2中剩下的元素倒回到stack1中,即实现一次出队。
3、代码
package com.ypj.java;
import java.util.Stack;
public class StackQueue {
Stack<Integer> stack1 = new Stack<Integer>();
Stack<Integer> stack2 = new Stack<Integer>();
//由于队列是先进先出的,而栈是先进后出的,所以要用2个栈来实现队列的入队出队功能,队列的入队功能与栈的一样
public void push(int node) {
stack1.push(node);
}
//出队时,先将第一个栈中的元素全部弹出,并倒入到第二个栈中,将第二个栈中栈顶元素弹出,即实现一次出队
public int pop() {
if (stack1.empty()&&stack2.empty()){
throw new RuntimeException();
}
if (stack2.empty()){
while (!stack1.empty()){
stack2.push(stack1.pop());
}
}
return stack2.pop();
}
public static void main(String[] args) {
StackQueue stackqueue = new StackQueue();
int[] arr = {1,2,3,4,5,6};
for(int i=0;i<arr.length;i++){
stackqueue.push(arr[i]);
}
for(int i=0;i<arr.length;i++){
System.out.println(stackqueue.pop());
}
}
}
4、运行结果