两个栈实现队列
题目描述
用两个栈来实现一个队列,完成队列的Push和Pop操作。 队列中的元素为int类型。
分析
两个栈实现队列,队列是先进先出,栈是后进先出,则可以用一个栈用来入队,一个栈用于出队
入队:
直接把数据stack1.push();
出队:
把stack1的数据搬到stack2,再把stack2.pop(),则数据顺序就是我们需要的顺序了,但是在出队的 过程中需要分情况:
(1)当stack1和stack2都为空时,此时无数据可以出队。
(2)如果stack2为空,而且stack1不空,则把stack1的元素全部移到stack2,以便出队
(3)如果stack2不空,直接出队
代码实现:
package 牛客;/*
*@Author: helen
*@Date: 2021/4/24 9:03
*@Description:
*/
import java.util.Stack;
public class 两个栈实现队列 {
Stack<Integer> stack1 = new Stack<Integer>();//用于入队
Stack<Integer> stack2 = new Stack<Integer>();//用于出队
public void push(int node) {
stack1.push(node);
}
public int pop() {
if(stack2.isEmpty() && stack1.isEmpty()){
return -1;
}
if (stack2.isEmpty() && !stack1.isEmpty()) {
//如果stack2为空,而且stack1不空,则把stack1的元素全部移到stack2,以便出队
while (!stack1.isEmpty()) {
Integer node = stack1.pop();
stack2.push(node);
}
}//如果stack2不空,直接出队
return stack2.pop();
}
public static void main(String[] args) {
两个栈实现队列 obj = new 两个栈实现队列();
obj.push(1);
obj.push(2);
obj.push(3);
System.out.println(obj.pop());
System.out.println(obj.pop());
System.out.println(obj.pop());
}
}