肇砖oj题,仅供参考,不怕被钟sir封号三周你就抄
Description
编写一个 stack栈类,在上一题的基础上:
-
增加:带一个参数 s 的构造函数,s表示栈的初始大小。这个构造函数在最后输出一行:
"constructor 2"。它的意思是第2个构造函数,是为了区分第1个构造函数输出的 "constructing"
-
由于栈的存储空间不再固定大小了,请思考是否需要增加一个数据成员以记录当前的空间大小
-
增加:析构函数,如果有动态申请的内存,释放之
C++中,用 new 替代 malloc, delete 替代 free 。
Input
在你的main函数中,首先使用带参数的构造函数创建一个栈对象,栈的大小由输入的第一行的正整数s决定
第二行是命令的数量n
接下来n行,每行是一条命令
Output
对第3、4、5类命令,输出一行:该命令对应取得的结果
Sample Input
2 <---- 创建一个容量是2的栈
9 <---- 命令的数量
1 5
1 7
3 <---- 输出栈顶元素的值 7
1 9 <---- 栈已满,所以不做任何动作
2
2
2 <---- 栈已空,所以不做任何动作
4 <---- 栈已空,输出0
3 <---- 栈已空,没有动作
Sample Output
constructor 2
7
0
destructing
Author
#include<iostream>
using namespace std;
class stack{
private:
int top;
int *data,max;
public:
stack (int m){
data = new int [m];
max=m;
top=-1;
cout<<"constructor "<<2<<endl;
}
void push(int n){
if(top==max-1) return;
top++;
data[top]=n;
}
void gettop(){
if(top<=-1) top=-1;
else cout<<data[top]<<endl;
}
void pop(){
if(top<=0) top=-1;
else {
top--;
}
}
void size(){
cout<<top+1<<endl;
}
void output(){
int n;
if(top<=-1) return;
else{
for(n=0;n<=top;n++)
cout<<data[n]<<" ";
cout <<endl;}
}
~stack(){
delete[]data;
cout<<"destructing"<<endl;
}
};
int main(){
int n;
cin>>n;
int num,i,ch,j;
cin>>num;
stack s(n);
for(i=1;i<=num;i++){
cin>>ch;
if(ch==1){
cin>>j;
s.push(j);
}
if(ch==2) s.pop();
if(ch==3) s.gettop();
if(ch==4) s.size();
if(ch==5) s.output();
}
}