栈的顺序存储 c++

栈的顺序存储c++

#include<iostream>
using namespace std;

template<class T>
class sqlist {
public:
	sqlist(int n); //创建
	~sqlist();
	void travel_sqlist();//遍历
	int len_sqlist();
	bool isempty();
	bool ispull();
	bool push_back(T e);//入栈
	T pop_back(T &e);	//出栈
	//T valua;	//栈值

private:
	T *elem;	//栈底指针
	int top;	//栈顶位置
	int len;	//顺序栈长度
	int maxsize;//顺序栈的最大容量
};
//创建顺序栈
template<class T>
sqlist<T>::sqlist(int n)
{
	this->elem = new T[n];
	this->top = -1;		//初始位置为0
	
	this->maxsize = n;	

}
//析构,删除顺序栈
template<class T>
sqlist<T>::~sqlist()
{
	delete this->elem;
	this->elem = NULL;			//删除elem,并将elem指向 NULL
}
//遍历顺序栈
template<class T>
void sqlist<T>::travel_sqlist()
{
	for (int i = this->top; i >= 0; i--)
	{
		cout << this->elem[i] << " ";
	}cout << endl;
}
//判空
template<class T>
bool sqlist<T>::isempty()
{
	return this->top == -1;//栈顶等于0
}
//判满
template<class T>
bool sqlist<T>::ispull()
{
	return this->top == this->maxsize - 1; //栈底等于最大容量
}
//顺序栈长度
template<class T>
int sqlist<T>::len_sqlist()
{
	return this->top + 1;
}

//入栈
template<class T>
bool sqlist<T>::push_back(T e)
{
	if (this->ispull())  //栈满则不能插入
		return 0;
	else
	{
		this->top++;
		this->elem[this->top] = e;

		return 1;
	}
}
//出栈
template<class T>
T sqlist<T>::pop_back(T &e)
{
	if (this->isempty())
		return 0;
	else
	{
		e = this->elem[this->top];
		this->top--;
		return 1;
	}
}


//主函数测试
int main()
{
	sqlist<int> s(8);
	int e = 0;
	cout << "请输入要录入的4个元素" << endl;
	for (int i = 0; i < 4; i++)
	{
		int temp_x;
		cin >> temp_x;
		s.push_back(temp_x);

	}

	if (s.isempty())
		cout << "是空顺序栈" << endl;
	else
		cout << "不是空顺序栈" << endl;

	int Length = s.len_sqlist();
	cout << "顺序栈的长度为:\n" << Length << endl;

	s.travel_sqlist();			 //遍历输出数据

	s.pop_back(e);
	s.travel_sqlist();

	system("pause");
	return 0;
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值