zoukankan      html  css  js  c++  java
  • 剑指offer--面试题21

    题目:设计包含min函数的栈,pop(),push(),min()的时间复杂度均为O(1)

    自己所写代码如下:(写‘栈’的代码还是有些不熟练!)

    #include <iostream>
    
    using namespace std;
    
    const int MAX = 100;
    
    class Stack
    {
    private:
        int values[MAX];
        int topindex;
        int minvalue;
        int minSecvalue;
    
    public:
        Stack();
        virtual ~Stack();
    
        int top() const;
        void push(int n);
        void pop();
        int min();
        bool empty() const;
    };
    
    Stack::Stack()
    {
        topindex = 0;
        minvalue = INT_MAX;
        minSecvalue = INT_MAX;
    }
    
    Stack::~Stack()
    {
    }
    
    bool Stack::empty() const
    {
        return topindex == 0;
    }
    
    int Stack::top() const
    {
        int toptemp = topindex;
        if(!empty())
        {
            --toptemp;
            return values[toptemp];
        }
        else
        {
            cerr<<"Stack is empty!"<<endl;
            return INT_MAX;
        }
    }
    
    void Stack::push(int n)
    {
        if(topindex < MAX)
        {
            values[topindex++] = n;
            if(minvalue > n)
            {
                minSecvalue = minvalue;
                minvalue = n;
            }
        }
        else
            cerr<<"Stack is full!"<<endl;
    }
    
    void Stack::pop()
    {
        if(!empty())
        {
            topindex--;
            if(values[topindex] == minvalue)
                minvalue = minSecvalue;
        }
        else
            cerr<<"Stack is empty!"<<endl;
    }
    
    
    int Stack::min()
    {
        if(!empty())
            return minvalue;
        else
        {
            cerr<<"Stack is empty!"<<endl;
            return INT_MAX;
        }
    }
    #include "stdafx.h"
    #include <iostream>
    #include "Stack.h"
    
    using namespace std;
    
    int main()
    {
        Stack st;
        for(int i=1; i<=10; i++)
            st.push(i);
        int top = st.top();
        cout<<top<<endl;
        int min = st.min();
        cout<<min<<endl;
        st.pop();
        st.pop();
        top = st.top();
        cout<<top<<endl;
        st.push(2);
        top = st.top();
        cout<<top<<endl;
        min = st.min();
        cout<<min<<endl;
    
        return 0;
    }
    清醒时做事,糊涂时读书,大怒时睡觉,独处时思考; 做一个幸福的人,读书,旅行,努力工作,关心身体和心情,成为最好的自己 -- 共勉
  • 相关阅读:
    Java牛角尖问题之static 静态变量和静态代码块的执行顺序
    蓝桥杯 蚂蚁爬楼梯 递归解最短路程问题
    动态规划系列题目学习
    使用Excel快速生成html表格
    C#使用out输出结果
    C#和sql语句中切割函数SUBSTRING的用法和区别
    C# 对DataTable进行操作
    自动生成表创建sql
    .net core获取根目录并转化字符串
    .net core从配置中读取数据并实例对象
  • 原文地址:https://www.cnblogs.com/hello-yz/p/3256293.html
Copyright © 2011-2022 走看看