用两个栈实现队列

给你一囗甜甜゛ 提交于 2019-12-05 06:52:30

用两个栈实现队列

用两个栈来实现一个队列,完成队列的Push和Pop操作。 队列中的元素为int类型。

代码实现

package 剑指offer;import java.util.Stack;/** * @author WangXiaoeZhe * @Date: Created in 2019/11/22 15:07 * @description: */public class Main4 {    public static void main(String[] args) {    }    Stack<Integer>stack1=new Stack<>();    Stack<Integer>stack2=new Stack<>();    /**     * 将元素压倒栈1中     */    public void push(int node){        stack1.push(node);    }    public int pop(){        /**         * 将栈1中的元素压倒栈2中         */        while(!stack1.isEmpty()){            stack2.push(stack1.pop());        }        /**         * 第一次出队         */        int first = stack2.pop();        /**         * 然后再将栈2剩下的元素倒入到栈1中         */        while (!stack2.isEmpty()){            stack1.push(stack2.pop());        }        /**         * 完成以此出队         */        return first;    }}
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!