//第二次上机第一题,栈的简单操作
1 //============================================================================ 2 // Name : 上机2.1.cpp 3 // Author : menglei 4 // Version : 5 // Copyright : Your copyright notice 6 // Description : Hello World in C++, Ansi-style 7 //============================================================================ 8 9 #include <iostream> 10 using namespace std; 11 12 template<class T> 13 class mStack{ //call a stack 14 private: 15 int size; 16 T *stackArray; 17 int top; 18 public: 19 mStack(){ 20 size = 100; 21 top = -1; 22 stackArray = new T[100]; 23 } 24 T pop(){ 25 if(top==-1){ 26 cout<<"stack is empty ,can't pop!"<<endl; 27 return NULL; //返回NULL会有问题,但编译能通过 28 } 29 top--; 30 return stackArray[top]; 31 } 32 int push(T value){ 33 if(top==size){ 34 cout<<"stack is full ! can't push !"<<endl; 35 return -1; 36 } 37 stackArray[top++]= value; 38 return 1; 39 } 40 T getTop(void){ 41 if(top==-1){ 42 cout<<"stack is empty! "<<endl; 43 return NULL; 44 } 45 return stackArray[top-1]; 46 } 47 }; 48 49 int main() { 50 mStack <char> m; 51 m.push('c'); 52 cout<<"top element is:"<<m.getTop()<<endl; 53 m.push('s'); 54 cout<<"top element is:"<<m.getTop()<<endl; 55 m.push('d'); 56 cout<<"top element is:"<<m.getTop()<<endl; 57 m.push('n'); 58 cout<<"top element is:"<<m.getTop()<<endl; 59 m.pop(); 60 cout<<"top element is:"<<m.getTop()<<endl; 61 return 0; 62 } 63
运行结果:
转载文章请注明出处: http://www.cnblogs.com/menglei/