实现stack功能
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 | class CStack { public : CStack(); //建立一个10个元素的栈 CStack( int s); //建立一个具有 s个元素的栈 CStack(CStack &r_s); //注意,没有重载赋值操作符 int get( int index); //返回下标为index 的栈元素 void push( int n); //进栈,top加1,把n的值存入栈顶 int isEmpty(); //判断栈是否为空,空则返回1,否则返回0 int isFull(); //判断栈是否是满的,空则返回1,否则返回0 int pop(); //出栈,返回栈顶元素,top减1 ~CStack(); //析构函数,释放在构造时申请的空间 private : int *a; int size; //栈的大小 int top; //指向栈顶 }; #include <iostream> using namespace std; void PopAll(CStack &stack) { while (!stack.isEmpty()) cout << stack.pop() << " " ; cout << endl; } CStack::CStack() :size(10), top(-1) { cout << "Constructor" << endl; a = new int [size]; } CStack::CStack( int s) : size(s), top(-1) { cout << "Constructor" << endl; a = new int [size]; } CStack::CStack(CStack &r_s) : size(r_s.size), top(r_s.top) { cout << "copy Constructor" << endl; a = new int [size]; memcpy (a, r_s.a, size * sizeof ( int )); } CStack::~CStack(){ PopAll(* this );cout << "Distructor" << endl; delete [] a; } int CStack::get( int index){ if (index >= 0 && index < top) return a[index]; else return -1; //-1作为返回错误?还是抛出异常? } void CStack::push( int n){ if (!isFull()) a[++top] = n; } int CStack::pop(){ if (!isEmpty()) return a[top--]; } int CStack::isEmpty(){ if (-1 == top) return 1; else return 0; } int CStack::isFull(){ if (top + 1 == size) return 1; else return 0; } #include <iostream> using namespace std; void GetNDataToStack(CStack &stack, unsigned int n) { while (n--) { int DataGet; cin >> DataGet; stack.push(DataGet); } } int main() { int nLoop; cout << "输入要构造几组数据:" ; cin >> nLoop; for ( int index = 0; index < nLoop; ++index) { cout << "输入要多少个数据存储:" ; unsigned int nDataCount; cin >> nDataCount; CStack stack(nDataCount); GetNDataToStack(stack, nDataCount); } return 0; } |
【推荐】还在用 ECharts 开发大屏?试试这款永久免费的开源 BI 工具!
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步