zoukankan      html  css  js  c++  java
  • 剑指 Offer 09. 用两个栈实现队列

    用两个栈实现一个队列。队列的声明如下,请实现它的两个函数 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 次调用

    来源:力扣(LeetCode)
    链接:https://leetcode-cn.com/problems/yong-liang-ge-zhan-shi-xian-dui-lie-lcof
    著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

    1.两个栈来回倒腾

    
    class CQueue {
    public:
        stack <int> st1,st2;
    
        CQueue() {
            while (!st1.empty()){
                st1.pop();
            }
            while (!st2.empty()){
                st2.pop();
            }
        }
        
        void appendTail(int value) {
            st1.push(value);
        }
        
        int deleteHead() {
            if (st1.empty()){
                return  -1;
            }
    
            while (!st1.empty()){
                st2.push(st1.top());
                st1.pop();
            }
            
            int  ret = st2.top();
            st2.pop();
    
            while (!st2.empty()){
                st1.push(st2.top());
                st2.pop();
            }
    
            return ret;
        }
    };
    
    

    2.更好的思路,删除时,检查栈2,若空,把栈1倒回栈2,然后pop,若还空,返回-1

    class CQueue {
        stack<int> stack1,stack2;
    public:
        CQueue() {
            while (!stack1.empty()) {
                stack1.pop();
            }
            while (!stack2.empty()) {
                stack2.pop();
            }
        }
        
        void appendTail(int value) {
            stack1.push(value);
        }
        
        int deleteHead() {
            // 如果第二个栈为空
            if (stack2.empty()) {
                while (!stack1.empty()) {
                    stack2.push(stack1.top());
                    stack1.pop();
                }
            }
            if (stack2.empty()) {
                return -1;
            } else {
                int deleteItem = stack2.top();
                stack2.pop();
                return deleteItem;
            }
        }
    };
    
    
  • 相关阅读:
    How the Data stored in computer?
    WinForm Vs WPF, COM/COM+ Vs .Net Assembly, COM/COM+ in ASP.Net, ... ...
    [Wonderful Explanation] ContextBound Objects and Remoting
    command
    compile the source code for specific device
    compile Android cm10.1
    Android Lint erroneously thinks min SDK version is 1
    wine Program File
    adb push framework.jar /system/framework
    Degrade ADT in Eclipse
  • 原文地址:https://www.cnblogs.com/xgbt/p/13211433.html
Copyright © 2011-2022 走看看