两个栈实现队列
Posted 雪浪snowWave
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了两个栈实现队列相关的知识,希望对你有一定的参考价值。
题目:用两个栈来实现一个队列,完成队列的Push和Pop操作。 队列中的元素为int类型。
思路:队列先进先出,栈后进后出,那么入队操作就可以使简单的push到一个栈中,而pop操作就需要把一个栈里所有元素弹到另一个栈里,然后pop栈顶
Stack<Integer> stack1 = new Stack<Integer>(); Stack<Integer> stack2 = new Stack<Integer>(); public void push(int node) { stack2.push(node); } public int pop() { //出队栈不为空!!! if(stack1.empty()){ while(!stack2.empty()){ stack1.push(stack2.pop()); } } return stack1.pop(); }
以上是关于两个栈实现队列的主要内容,如果未能解决你的问题,请参考以下文章