剑指offer--面试题21

时间:2022-12-03 04:25:54

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

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

#include <iostream>

using namespace std;

const int MAX = ;

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 = ;
minvalue = INT_MAX;
minSecvalue = INT_MAX;
} Stack::~Stack()
{
} bool Stack::empty() const
{
return topindex == ;
} 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=; i<=; 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();
top = st.top();
cout<<top<<endl;
min = st.min();
cout<<min<<endl; return ;
}