E. Stack(类与构造)
题目描述
上面是栈类的定义,栈是一种具有先进后出特点的线性表,请根据注释,完成类中所有方法的实现,并在主函数中测试之。 堆栈类的说明如下: 1. 堆栈的数据实际上是保存在数组a中,而a开始是一个指针,在初始化时,根据实际需求将a动态创建为数组,数组长度根据构造函数的参数决定。 2.size实际上就是数组的长度,当使用无参构造则size为10,当使用有参构造则size为s、 3.top表示数组下标,也表示数组中下一个存放数据的空白位置。 4.push操作表示堆栈的数组存放一个数据,例如一开始数组为空,则top为0,当有数据要入栈时,把数据存放在a[top]的位置,然后top加1指向下一个空白位置、数据进栈只能从栈顶进。 5.pop操作表示一个数据要出栈,数据出栈只能从栈顶出,先把top减1指向栈顶数据,然后把数据返回。 6.判断堆栈空的条件是top是否等于0,判断堆栈满的条件是top是否等于size 输入 测试数据的组数 t 第一个栈的大小 第一个栈的元素列表,将该列表的元素依次进栈 .......... 输出 将栈元素依次出栈 输入样例1 2 5 1 2 3 4 5 7 -1 2 8 0 -3 1 3 输出样例1 Constructor. 5 4 3 2 1 Destructor. Constructor. 3 1 -3 0 8 2 -1 Destructor.
该题主要考察运用类的知识模拟栈,主要注意下标的变化避免数组越界以及格式化输出
#define _CRT_SECURE_NO_WARNINGS
#include<iostream>
#include<algorithm>
#include<string>
#include<vector>
#include <iomanip>
#include<cmath>
#include<cstring>
#include<cctype>
#include<queue>
#include<set>
using namespace std;
class cstack
{
public:
cstack();
cstack(int s);
cstack(cstack& r_s);
int get(int index);
void push(int n);
int isempty();
int isfull();
int pop();
~cstack();
private:
int* a;
int size;
int top;
};
cstack::cstack()
{
top = 0;
size = 10;
cout << "Constructor." << endl;
a = new int[10];
}
cstack::cstack(int n)
{
top = 0;
size = n;
cout << "Constructor." << endl;
a = new int[n];
}
int cstack::get(int index)
{
return a[index];
}
void cstack::push(int n)
{
a[top] = n;
top++;
}
int cstack::isempty()
{
if (top <= 0)
{
return 1;
}
else
{
return 0;
}
}
int cstack::isfull()
{
if (top == size)
{
return 1;
}
else
{
return 0;
}
}
int cstack::pop()
{
top--;
return a[top];
}
cstack::~cstack()
{
delete[]a;
}
int main()
{
int t,n,num,sign=1;
cin >> t;
while (t--)
{
sign=1;//记得重新初始化
cin >> n;
cstack st1(n);
for (int i = 0; i < n; i++)
{
cin >> num;
st1.push(num);
}
while (!st1.isempty())
{
if (sign)
{
cout << st1.pop();
sign = 0;
}
else
{
cout << ' ' << st1.pop();
}
}
cout << endl;
cout << "Destructor." << endl;
}
return 0;
}