C++实现stack【栈】
要求:
//****file: stack.h
/*
对stack进行初始化
检查stack为空,或已满
将整数压入到stack中
从stack里弹出整数
不移除任何袁术,讲过stack的内容输出到标准输出
Stack类的私有成员如下:
一个用于打印错误信息的私有哦成员函数
三个私有数据成员构成了stack类的private实现,此实现为类接口提供支持。
*/
类的实现
1 #include <iostream> 2 using namespace std; 3 4 5 class Stack{ 6 public : 7 enum {MaxStack = 5}; 8 //初始化栈,栈为空 9 void init () {top = -1;} 10 11 void push (int n){ 12 if (isFull()){ 13 errMsg("Full stack .cant push"); 14 return ; 15 } 16 arr[++top ] =n; 17 } 18 19 int pop() { 20 if (isEmpty () ){ 21 errMsg("Empty stack . Popping dummy value."); 22 return dummy_val; 23 } 24 25 return arr[top-- ]; 26 } 27 //检查statck是否为空 28 bool isEmpty() {return top <0 ;} 29 //检查stack是否已满 30 bool isFull() {return top >= MaxStack - 1;} 31 32 //dump倾倒 , 按照从stack顶端到底端的次序,依次将Stack的内容输出到标准输出 33 void dump () { 34 for (int i = top; i >= 0; i--) 35 cout << 't' << arr[i] << '\n'; 36 } 37 38 39 private : 40 void errMsg(const char * msg) const { 41 cerr << "\n*** Stack operation failure : "<< msg << '\n'; 42 } 43 44 int top; 45 int arr[ MaxStack ]; 46 int dummy_val; 47 48 };
测试代码如下:
#include <iostream> #include "stack.h" int main() { Stack s1; s1.init(); s1.push(9); s1.push(4); s1.dump(); cout << "Popping " << s1.pop() << '\n'; s1.dump(); s1.push(8); s1.dump(); s1.pop();s1.pop(); s1.dump(); s1.pop(); s1.dump(); s1.push(3); s1.push(5); s1.dump(); for (unsigned i = 0; i <Stack::MaxStack; i++) s1.push(1); s1.dump(); return 0; }
调试结果:
/* t4 t9 Popping 4 t9 t8 t9 *** Stack operation failure : Empty stack . Popping dummy value. t5 t3 *** Stack operation failure : Full stack .cant push *** Stack operation failure : Full stack .cant push t1 t1 t1 t5 t3 -------------------------------- Process exited with return value 0 Press any key to continue . . . */