2设计包含min函数的栈

来源:互联网 发布:java事务的四个特性 编辑:程序博客网 时间:2024/06/07 06:30

#include <iostream>

using namespace std;

class stack
{
public:
    stack(int num);
    ~stack();
    void push(int num);
    int pop();
    int min();
    void error(const char * s);
private:
    int size;
    int top;
    int* value;
};

stack::stack(int num)
{
    size = num;
    value = new int[num];
    top = size;
}

stack::~stack()
{
    delete value;
}

void stack::error(const char* s)
{
    cout<<s<<endl;
    return;
}
int stack::pop()
{
    if(top >= size)
        error("space is empty");
    int num = value[top++];
    return num;
}

void stack::push(int num)
{
    if(top <= 0)
        error("out of space");
    else
    {
        if(top == size)
        {
            value[--top] = num;
        }
        else
        {
            if(num > value[top])
            {
                int tmp = pop();
                value[--top] = num;
                value[--top] = tmp;
            }
            else
            {
                value[--top] = num;
            }
        }
    }
}

int stack::min()
{
    return pop();
}

int main()
{
    stack s(5);

    s.push(19);
    s.pop();
    s.push(11);
    s.push(8);
    s.push(89);
    s.push(12);
    s.pop();
    s.push(1);
    s.push(22);

    cout<<s.min()<<endl;

    return 0;
}

原创粉丝点击