zoukankan      html  css  js  c++  java
  • 双栈实现队列

    俩个栈实现队列的功能,头部删除,尾部添加,是否为空,返回队头

    /**
     * 用俩个栈实现队列
     */
    public class MyQueue {
    
        Stack<Integer> stack1,stack2;
    
        public MyQueue() {
            this.stack1 = new Stack<>();//主栈
            this.stack2 = new Stack<>();//辅助栈
        }
        /** 添加元素到队尾 */
        public void add(int x){
            stack1.push(x);
    
        }
    
        /** 删除队头的元素并返回 */
        public int deleteHead(){
            // 先调用 peek 保证 s2 非空
            getHead();
            return stack2.pop();
        }
    
        /** 返回队头元素 */
        public int getHead(){
            //如果s2不为空,返回s2栈顶元素。如果为空将s1的元素都加入s1中,返回s2栈顶元素
            if(stack2.isEmpty()){
                while (!stack1.isEmpty())
                    stack2.push(stack1.pop());
            }
            return stack2.peek();
        }
    
        /** 判断队列是否为空 */
        public boolean empty(){
            return stack1.isEmpty()&&stack2.isEmpty();
        }
    
        public static void main(String[] args) {
            MyQueue myQueue=new MyQueue();
            myQueue.add(1);
            myQueue.add(2);
            myQueue.add(3);
            myQueue.add(4);
            System.out.println(myQueue.getHead());
            myQueue.deleteHead();
            System.out.println(myQueue.getHead());
    
        }
    }
    
  • 相关阅读:
    laravel安装
    redis缓存设置和读取
    window下装redis扩展(以php5.5为例)
    静态缓存
    原生js发送ajax请求
    数据库查询语句面试
    Cookie与Session
    面试题-一个for循环输出一个棱形
    编程题:利用for循环打印 9*9 表?
    java面试题之分析(二)
  • 原文地址:https://www.cnblogs.com/treasury/p/12752410.html
Copyright © 2011-2022 走看看