肇砖oj题,仅供参考,不怕被钟sir封号三周你就抄
Description
编写一个 stack栈类,在上一题的基础上:
-
增加:拷贝构造函数,实现深拷贝。函数最后要输出一行:copy constructor
Input
输入分两部分:第一部分是作用在第一个栈对象的 n 条命令,第二部分是作用在第二个栈对象的 m 条命令。
第一行是一个整数 S,表示创建一个容量为 S 的栈对象。
接下来一行是一个整数 n,表示接下来 n 行是作用在第一个栈对象的 n 条命令
接下来 n 行,每行是一条命令
然后在 main 函数中,用拷贝构造函数创建出第二个栈对象
接下来是一个整数 p,表示接下来 p 行是作用在第二个栈对象的 p 条命令
接下来 p 行,每行是一条命令
Output
对第3、4、5类命令,输出一行:该命令对应取得的结果
Sample Input
4 <---- 创建一个容量 S=4 的栈
6 <---- 表示作用在第1个对象的 n 条命令
1 5
1 7
1 9
4 <---- 栈内有3个元素,输出3
2
3 <---- 由于弹走了9,所以输出栈顶元素的值 7
12 <---- 表示作用在第2个对象的 m 条命令
2
3 <---- 由于弹走了7,所以输出栈顶元素的值 5
2
2 <---- 栈已空,所以不做任何动作
1 10
1 11
1 12
1 13
1 14 <---- 栈已满,所以不做任何动作
1 15 <---- 栈已满,所以不做任何动作
3 <---- 输出栈顶元素13
5 <---- 输出 10 11 12 13
Sample Output
constructor 2 <---- 第一个对象的构造函数输出
3
7
copy constructor <---- 第二个对象的拷贝构造函数输出
5
13
10 11 12 13
destructing <---- 第二个对象的析构函数输出
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;
}
stack(stack &p){
max=p.max;
data=new int [max];
for(top=0;top<max;top++)
data[top]=p.data[top];
top=p.top;
cout<<"copy constructor"<<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;
}
};
void xh(int num,stack &s){
int i,ch,j;
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();
}
}
int main(){
int n;
cin>>n;
stack s(n);
int num,i,ch,j;
cin>>num;
xh(num,s);
stack p(s);
cin>>num;
xh(num,p);
return 0;
}