肇砖oj题,仅供参考,不怕被钟sir封号三周你就抄
Description
本题与《编写一个stack类.part.1》要求相同,只有红色字体处不同:
编写一个 stack栈类,约定:
1. 封装数据和操作
2. 数据成员为私有属性,包括:
-
data:保存栈内元素,栈内元素类型为int
-
top: 指示栈顶位置
3. 成员函数为公有属性,包括:
-
默认构造函数,完成初始化动作,栈的默认大小是5。最后输出一行:constructing
-
析构函数只输出一行:destructing
-
top( &v ),函数没有返回值,如果栈空,抛出stackEmpty对象,否则,参数v带回栈顶元素的值
-
pop(),如果栈空,抛出stackEmpty对象,否则,弹走栈顶元素
-
push( v ),如果栈满,抛出stackFull对象;如果栈未满,参数v的值进栈
-
size(),返回当前栈内元素个数,如果栈空,返回0
-
output(),自栈底到栈顶,输出栈内元素,每一个元素后面跟一个空格,作为分隔。最后换行。如果栈空,没有输出
4. 实现两个异常类 stackFull 和 stackEmpty 。stackFull类在栈满当发生push动作时触发;stackEmpty在栈空当发生pop动作或top动作时触发。
Input
多条命令,每种命令定义如下:
-
1 a :表示把元素a压入栈
-
2 :表示弹走栈顶元素
-
3 :表示读取栈顶元素的值
-
4 :表示输出当前栈内元素的个数
-
5 :表示调用output()函数
输入的第一行是命令的数量n
接下来n行,每行是一条命令
Output
对第3、4、5类命令,输出一行:该命令对应取得的结果
Sample Input
21
3 <---- 触发stackEmpty对象
1 3
1 5
1 7
3
2
4
2
1 9
5
3
1 10
1 11
1 12
1 13 <---- 触发stackFull对象
2
2
2
2
2
2 <---- 触发stackEmpty对象
Sample Output
constructing <---- 默认构造函数输出
stack empty <---- stackEmpty对象输出
7 <---- 当前栈顶元素是7
2 <---- 弹走了7,所以只剩下2个元素
3 9 <---- 弹走了5,压入了9,所以栈内的元素是3,9
9 <---- 栈顶元素是9
stack full, 13 not pushed. <---- stackFull对象输出
stack empty <---- stackEmpty对象输出
destructing <---- 析构函数输出
Author
#include<iostream>
using namespace std;
class stackEmpty{
public: void out(){cout<<"stack empty"<<endl;}
};
class stackFull{
public: void out(int j){cout<<"stack full, "<<j<<" not pushed."<<endl;}
};
class stack{
private:
int top;
int *data,max;
public:
stack (int m){
data = new int [m];
max=m;
top=-1;
cout<<"constructing"<<endl;
}
void push(int n){
if(top==max-1) throw stackFull();
top++;
data[top]=n;
}
void gettop(){
if(top<=-1) throw stackEmpty();
else cout<<data[top]<<endl;
}
void pop(){
if(top<=-1) throw stackEmpty();
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 num,i,ch,j;
cin>>num;
stack s(5);
for(i=1;i<=num;i++){
cin>>ch;
if(ch==1){
cin>>j; try{ s.push(j); }
catch(stackFull &e) { e.out(j); }
}
if(ch==2){
try{ s.pop(); }
catch(stackEmpty &e) { e.out(); }
}
if(ch==3){
try{ s.gettop(); }
catch(stackEmpty &e) { e.out(); }
}
if(ch==4) s.size();
if(ch==5) s.output();
}
return 0;
}