E. Stack(类与构造)

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;
}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

ZZZWWWFFF_

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值