• 设计一个具有min函数的stack


    此题目来自于Crack the Coding Interview 3-2

    3 2  How would you design a stack which, in addition to push and pop, also has a function min which returns the minimum element? Push, pop and in should all operate in O(1) time.

    思路是弄2个stack,一个realStack,存放真正的数据;另外一个是minStack,对于minStack元素中的每一个元素的意义是:push到该位置的时候,当前最小元素的值。每次push进新元素的时候,更新minStack的值;每次pop的时候,由于minStack的定义,所以只需把minStack和realStack一起进行一次pop操作就好了。

    #include <iostream>
    #include <stack>
    using namespace std;
    
    class StackWithMin{
    public:
        void push(int value);
        void pop();
        int min();
        int top();
    private:
        stack<int> realStack;
        stack<int> minStack;
    };
    
    void StackWithMin::push(int value)
    {
        int currMin = 0;
        if (!minStack.empty())
            currMin = minStack.top();
        else
            currMin = INT_MAX;
    
        if (value < currMin)
            minStack.push(value);
        else
            minStack.push(minStack.top());
    
        realStack.push(value);
    }
    
    void StackWithMin::pop()
    {
        if (realStack.empty() || minStack.empty())
        {
            cout<<"stack empty!"<<endl;
                return;
        }
        realStack.pop();
        minStack.pop();
    }
    
    int StackWithMin::min()
    {
        if (realStack.empty() || minStack.empty())
        {
            cout<<"stack empty!"<<endl;
                return INT_MAX;
        }
        return minStack.top();
    }
    
    int StackWithMin::top()
    {
        if (realStack.empty() || minStack.empty())
        {
            cout<<"stack empty!"<<endl;
                return -1;
        }
    
        return realStack.top();
    }
    
    int main()
    {
        StackWithMin stk;
        for (int i = 0; i < 10; i++)
        {
            int value = rand()%150;
            cout<<"Pushing : "<<value<<endl;
            stk.push(value);
        }
        cout<<"Push 10 Elements and current min is : "<<stk.min()<<endl<<endl;
    
        for (int i = 0; i < 5; i++)
        {
            int value = stk.top();
            cout<<"Poping : "<<value<<endl;
            stk.pop();
        }
        cout<<"After pop 5 Elements, current min is : "<<stk.min()<<endl;
    
        return 0;
    }

    EOF

  • 相关阅读:
    Salesforce PDF打印
    Salesforce Visualforce分页
    Salesforce 开发实践探索
    Salesforce 锁定记录
    Salesforce 通过代码实现权限共享
    Salesforce Aura开发 Component表单初解
    phpqrcode生成动态二维码简单实例
    PHP结合zyupload多功能图片上传实例
    PHP程序员的技术成长规划 第三阶段:高级阶段
    PHP程序员的技术成长规划 第二阶段:提高阶段
  • 原文地址:https://www.cnblogs.com/lihaozy/p/2809840.html
Copyright © 2020-2023  润新知