1 // Stack.cpp : 定义控制台应用程序的入口点。 2 // 3 4 #include "stdafx.h" 5 #include <iostream> 6 using namespace std; 7 8 template <class Type> 9 struct Stack10 {11 private:12 Type *_stack;13 int _top;14 int _min;15 int _size;16 17 18 public:19 Stack(const Type &size):_size(size),_top(0),_min(0)20 { 21 _stack = new Type[size];//(Type*)malloc(sizeof())22 }23 void push(const Type &value)24 {25 26 if(_top == 0)27 {28 _min = value;29 }30 else if(_top == _size)31 {32 cout<<"Push failed,the stack is full"<<endl;33 return;34 }35 _stack[_top++] = value-_min;36 if(value < _min)37 { 38 _min = value;39 }40 41 }42 Type pop()43 {44 if(_top == 0)45 {46 cout<<"Pop failed,the stack is emply."<<endl;47 return -1;48 }49 Type popvalue;50 if(_stack[--_top]<0)51 {52 popvalue = _min;53 _min = _min-_stack[_top];54 }55 else56 {57 popvalue = _min + _stack[_top];58 }59 return popvalue;60 }61 Type min()62 {63 return _min;64 }65 66 };67 68 int _tmain(int argc, _TCHAR* argv[])69 {70 Stack<int> sk(30);71 sk.push(8);72 sk.push(7);73 sk.push(6);74 sk.push(5);75 sk.push(9);76 sk.push(4);77 sk.push(3);78 79 cout<<sk.min()<<endl;//380 cout<<sk.pop()<<endl;//381 cout<<sk.min()<<endl;//482 cout<<sk.pop()<<endl;//483 cout<<sk.min()<<endl;//584 cout<<sk.pop()<<endl;//985 cout<<sk.min()<<endl;//586 cout<<sk.pop()<<endl;//587 cout<<sk.min()<<endl;//688 cout<<sk.pop()<<endl;//689 cout<<sk.min()<<endl;//790 cout<<sk.pop()<<endl;//791 cout<<sk.min()<<endl;//892 cout<<sk.pop()<<endl;//893 94 return 0;95 }96 97
作者:HarlanC
博客地址:http://www.cnblogs.com/harlanc/
个人博客: http://www.harlancn.me/
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出, 原文链接
如果觉的博主写的可以,收到您的赞会是很大的动力,如果您觉的不好,您可以投反对票,但麻烦您留言写下问题在哪里,这样才能共同进步。谢谢!
版权声明
本文仅代表作者观点,不代表百度立场。
本文系作者授权百度百家发表,未经许可,不得转载。



