堆栈类的设计

mac2025-03-31  6

/*堆栈类的设计: (1)在定义对象时能够确定堆栈的长度 (2)给出push和pop函数的定义 (3)通过运算符的重载,实现对堆栈是否为空的判断 (4)定义变化函数,用于返回堆栈的长度 (5)通过函数的递归调用,来计算堆栈中数据为0的元素的个数 (6)给出main函数,在函数体中合理地调用上述每一个函数 */ #include<iostream> using namespace std; class stack { int size; int *top; int *base; public: stack(int n) { top=base=new int[n]; size=n; } void push(int x) { if(top-base<size) *top++=x; } int pop() { if(top>base) return *--top; else return 0; } int operator!() { return (top==base); } operator int() { return size; } int *getbase() { return base; } int count(int *base) { static int c=0; if(base<top) { if(*base++==0) c++; count(base); } return c; } }; int main() { stack p(10); p.push(0); p.push(1); p.push(2); p.push(4); cout<<"堆栈的长度为:"<<endl; int length=p;cout<<length<<endl; if(!(!p)) { cout<<"堆栈中0的个数为:"<<endl; int n=p.count(p.getbase());cout<<n<<endl; } cout<<"栈顶元素为:"<<endl; int x=p.pop();cout<<x<<endl; }

最新回复(0)