题目描述:
用两个栈来实现一个队列,完成队列的Push和Pop操作。 队列中的元素为int类型。
code:
思路:栈为先进后出,对列为先进先出
import java.util.Stack; public class Solution { Stack<Integer> stack1 = new Stack<Integer>(); Stack<Integer> stack2 = new Stack<Integer>(); public void push(int node) { //入队列:直接把值放入stack1中 stack1.push(node); } public int pop() { //出队列 //如果两个栈都为空 if (stack1.empty() && stack2.empty()) { //这里返回-1,表示队列为空;也可抛出异常等 return -1; } //定义num用来存储出栈的值 int num = 0; //如果stack2为空 if (stack2.empty()) { //如果stack1不为空,把stack1中值逆序到stack2中 while (!stack1.empty()) { //stack1出栈,赋值到num num = stack1.pop(); //num入栈到stack2 stack2.push(num); } } //stack2出栈,赋值给num num = stack2.pop(); //返回num return num; } }