美文网首页剑指offer
08_用两个栈实现队列

08_用两个栈实现队列

作者: 是新来的啊强呀 | 来源:发表于2020-05-18 20:49 被阅读0次

    要求:声明如下,请实现它的两个函数appendTail和deleteHead,分别完成在队列尾部插入节点和在队列头部删除节点的功能。

    思路:
    入队:将元素进栈A
    出队:判断栈B是否为空,如果为空,则将栈A中所有元素pop,并push进栈B,栈B出栈;

    如果不为空,栈B直接出栈。

        Stack<Integer> stack1 = new Stack<Integer>();
        Stack<Integer> stack2 = new Stack<Integer>();
        public void push(int node) {
            // 栈一输入
            stack1.push(node);
        }
    
        public int pop() {
            // 如果两个队列都为空,则弹出错误
            if(stack1.empty()&&stack2.empty()){
                throw new RuntimeException("Queue is empty!");
            }
            // 栈2为空时
            if(stack2.size()<=0){
                // 栈一有数
                while(stack1.size()!=0){
                    stack2.push(stack1.pop());
                }
            }
            return stack2.pop();
        }
    

    相关文章

      网友评论

        本文标题:08_用两个栈实现队列

        本文链接:https://www.haomeiwen.com/subject/bqwpohtx.html