标签:
剑指offer第二十一题:包含min函数的栈
1 //============================================================================ 2 // Name : JZ-C-21.cpp 3 // Author : Laughing_Lz 4 // Version : 5 // Copyright : All Right Reserved 6 // Description : Hello World in C++, Ansi-style 7 //============================================================================ 8 9 #include <iostream> 10 #include <stdio.h> 11 #include <stack> 12 #include <assert.h> 13 using namespace std; 14 template<typename T> class StackWithMin { 15 public: 16 StackWithMin<T>(void) { 17 } 18 ; 19 ~StackWithMin<T>(void) { 20 } 21 ; //析构函数 22 void push(const T& value); 23 T& top(void); 24 const T& top(void) const; 25 void pop(void); 26 const T& min(void) const; 27 bool empty(void) const; 28 size_t size() const; 29 private: 30 std::stack<T> dataStack; //存放数据 31 std::stack<T> minStack; //存放最小值 32 }; 33 template<typename T> void StackWithMin<T>::push(const T& value) { 34 dataStack.push(value); //数据压入数据栈 35 if (minStack.size() == 0 || value < minStack.top()) { 36 minStack.push(value); //比较后压入最小值栈 37 } else { 38 minStack.push(minStack.top()); //若比最小值大,则重复压入最小值 39 } 40 } 41 template<typename T> void StackWithMin<T>::pop() { 42 assert(!minStack.empty() && !dataStack.empty()); //这里为什么要用assert?用法? 43 dataStack.pop(); 44 minStack.pop(); 45 } 46 template<typename T> const T& StackWithMin<T>::min() const { 47 assert(dataStack.size() > 0 && dataStack.size() > 0); 48 49 return minStack.top(); 50 } 51 52 template<typename T> T& StackWithMin<T>::top() { 53 return dataStack.top(); 54 } 55 56 template<typename T> const T& StackWithMin<T>::top() const { 57 return dataStack.top(); 58 } 59 template<typename T> bool StackWithMin<T>::empty() const { 60 return dataStack.empty(); 61 } 62 63 template<typename T> size_t StackWithMin<T>::size() const { 64 return dataStack.size(); 65 } 66 67 void Test(char* testName, const StackWithMin<int>& stack, int expected) { 68 if (testName != NULL) 69 printf("%s begins: ", testName); 70 71 if (stack.min() == expected) 72 printf("Passed.\n"); 73 else 74 printf("Failed.\n"); 75 } 76 int main(int argc, char** argv) { 77 StackWithMin<int> stack; 78 79 stack.push(3); 80 Test("Test1", stack, 3); 81 82 stack.push(4); 83 Test("Test2", stack, 3); 84 85 stack.push(2); 86 Test("Test3", stack, 2); 87 88 stack.push(3); 89 Test("Test4", stack, 2); 90 91 stack.pop(); 92 Test("Test5", stack, 2); 93 94 stack.pop(); 95 Test("Test6", stack, 3); 96 97 stack.pop(); 98 Test("Test7", stack, 3); 99 100 stack.push(0); 101 Test("Test8", stack, 0); 102 103 return 0; 104 }
标签:
原文地址:http://www.cnblogs.com/Laughing-Lz/p/5578825.html