1803 类设计练习4:构造函数、析构函数:编写一个stack类.part.2

肇砖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

John

 

#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();
    }
}

  • 0
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值