源代码
Stack.h
1 #include<iostream> 2 #include<cstring> 3 typedef char Stack_Data; //栈的数据类型 4 const int Stack_Size=50; //栈的最大存储量 5 using namespace std; 6 class Stack 7 { 8 private: 9 Stack_Data Data[Stack_Size]; 10 int Top; 11 public: 12 Stack(); //初始化栈 13 bool IsEmpty();//判空 14 bool IsFull();//判满 15 void Push(Stack_Data e);// 入栈 16 bool Pop(Stack_Data *e);//出栈 17 void GetTop(Stack_Data *e);//取栈顶元素 18 void Display();//展示函数 19 int TopLocation();//获取Top 20 }; 21 Stack::Stack() 22 { 23 Top=0; 24 } 25 bool Stack:: IsEmpty() 26 { 27 if(Top==0) 28 { 29 return true; 30 } 31 else 32 return false; 33 } 34 bool Stack::IsFull() 35 { 36 if(Top==Stack_Size-1) 37 { 38 return true; 39 } 40 else 41 return false; 42 } 43 void Stack::Push(Stack_Data e) 44 { 45 if(!IsFull()) 46 { 47 Top++; 48 Data[Top]=e; 49 cout<<"Success"<<endl; 50 } 51 else 52 cout<<"Stack OverFlow"<<endl; 53 } 54 bool Stack::Pop(Stack_Data *e) 55 { 56 if(!IsEmpty()) 57 { 58 *e=Data[Top]; 59 Top--; 60 cout<<"Success"<<endl; 61 return true; 62 } 63 else 64 cout<<"Defeat"<<endl; 65 return false; 66 } 67 void Stack::GetTop(Stack_Data *e) 68 { 69 if(!IsEmpty()) 70 { 71 *e=Data[Top]; 72 cout<<"Success"<<endl; 73 } 74 else 75 cout<<"Defeat"<<endl; 76 } 77 void Stack::Display() 78 { 79 if(!IsEmpty()) 80 { 81 int temp=Top; 82 while(temp) 83 { 84 cout<<"Data["<<temp<<"] "<<Data[temp]<<endl; 85 temp--; 86 } 87 } 88 else 89 cout<<"False"<<endl; 90 } 91 int Stack::TopLocation() 92 { 93 return Top; 94 }
测试代码
Main.cpp
1 int _tmain(int argc, _TCHAR* argv[]) 2 { 3 Stack obj; 4 bool t; 5 while(true) 6 { 7 cout<<"是否入栈 "<<endl; 8 cout<<"是 1"<<endl; 9 cout<<"否 0"<<endl; 10 cin>>t; 11 if(!t) 12 { 13 break; 14 } 15 Stack_Data e; 16 cout<<"请输入入栈元素"<<endl; 17 cin>>e; 18 obj.Push(e); 19 } 20 obj.Display(); 21 while(true) 22 { 23 cout<<"是否出栈 "<<endl; 24 cout<<"是 1"<<endl; 25 cout<<"否 0"<<endl; 26 cin>>t; 27 if(!t) 28 { 29 break; 30 } 31 Stack_Data e; 32 if(obj.Pop(&e)) 33 { 34 cout<<"出栈元素: "<<e<<endl; 35 } 36 } 37 obj.Display(); 38 cout<<obj.IsFull()<<endl; 39 cout<<obj.IsEmpty()<<endl; 40 Stack_Data e; 41 obj.GetTop(&e); 42 cout<<e<<endl; 43 cout<<obj.TopLocation()<<endl; 44 return 0; 45 }
测试结果