剑指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; }
清醒时做事,糊涂时读书,大怒时睡觉,独处时思考; 做一个幸福的人,读书,旅行,努力工作,关心身体和心情,成为最好的自己
-- 共勉