• 剑指offer_05:用两个栈实现队列


    用两个栈实现一个队列。队列的声明如下,请实现它的两个函数 appendTail 和 deleteHead ,分别完成在队列尾部插入整数和在队列头部删除整数的功能。(若队列中没有元素,deleteHead 操作返回 -1 )

    示例 1:
    输入:
    ["CQueue","appendTail","deleteHead","deleteHead"]
    [[],[3],[],[]]
    输出:[null,null,3,-1]

    示例 2:
    输入:
    ["CQueue","deleteHead","appendTail","appendTail","deleteHead","deleteHead"]
    [[],[],[5],[2],[],[]]
    输出:[null,-1,null,null,5,2]

    提示:
    1 <= values <= 10000
    最多会对 appendTail、deleteHead 进行 10000 次调用

    1、原始想法

    class CQueue {
        Stack<Integer> stack;
        Stack<Integer> helper;
        public CQueue() {
            stack=new Stack<Integer>();
            helper=new Stack<Integer>();
        }
        
        public void appendTail(int value) {
            stack.push(value);
        }
        
        public int deleteHead() {
            if(stack.isEmpty()){
                return -1;
            }
            while(!stack.isEmpty()){
                helper.push(stack.pop());
            }
            int res=helper.pop();
            while(!helper.isEmpty()){
                stack.push(helper.pop());
            }
            return res;
        }
    }
    
    /**
     * Your CQueue object will be instantiated and called as such:
     * CQueue obj = new CQueue();
     * obj.appendTail(value);
     * int param_2 = obj.deleteHead();
     */
    

    2、优化

    stack的底层是数组,有扩容和移位的问题。可以使用LinkedList来实现。

    class CQueue {
        LinkedList<Integer> stack;
        LinkedList<Integer> helper;
        public CQueue() {
            stack=new LinkedList<Integer>();
            helper=new LinkedList<Integer>();
        }
        
        public void appendTail(int value) {
            stack.addLast(value);
        }
        
        public int deleteHead() {
            if(!helper.isEmpty()){
                return helper.removeLast();
            }
            if(stack.isEmpty()){
                return -1;
            }else{
                while(!stack.isEmpty()){
                    helper.addLast(stack.removeLast());
                }
                return helper.removeLast();
            }
        }
    }
    
    /**
     * Your CQueue object will be instantiated and called as such:
     * CQueue obj = new CQueue();
     * obj.appendTail(value);
     * int param_2 = obj.deleteHead();
     */
    
  • 相关阅读:
    使用脚本改变树控件的行为 (转)点文本 收..
    (面包屑)SiteMapPath控件简化Web网站导航 (转)
    Web.config详解(转)
    SiteMap(站点地图)示例(转)
    url传递中文的解决方案总结(转)
    INI文件编程,WINAPI函数WritePrivateProfileString,GetPrivateProfileString(转帖)
    hdu 2708
    hdu 1709
    hdu 1045
    hdu 2714
  • 原文地址:https://www.cnblogs.com/xyz-1024/p/13974015.html
Copyright © 2020-2023  润新知