自定义stack类模版,实现empty?full?push,pop,gettop,clear,display

本文档提供了一个自定义的C++模板栈类实现,包括构造函数、析构函数以及各种操作方法如检查空栈、满栈、压栈、弹栈、获取栈顶元素、清除栈和显示栈内容的方法。通过示例代码展示了如何使用该栈类进行基本操作,并在main函数中进行了测试。
//stack.h定义
#include<iostream>
#include<cassert>
#ifndef STACK
#define STACK

template<class T>
class stack{
	int top;
	T *a;
	int cn;
public:
	stack(int c);
	~stack();
	bool empty()const;
	bool full()const;
	void push(const T &item);
	T gettop()const;
	void pop();
	void clear();
	void display(const stack<T> &s1);
};

template<class T>//初始化栈,栈顶top=-1
stack<T>::stack(int c){
	assert(c > 0);
	cn = c;
	a = new T[cn];//动态数组建立
	if (a!= 0)
		top = -1;
	else
		assert(a != 0);
}

template<class T>//析构函数调用清除动态数组
stack<T>::~stack(){
	delete[]a;
}

template<class T>//判空,top=-1则为空
bool stack<T>::empty()const{
	return(top == -1);
}

template<class T>//栈满判断
bool stack<T>::full()const{
	return(top == cn - 1);
}

template<class T>//压栈,首先判断是否栈满
void stack<T>::push(const T &item){
	assert(!full());
	a[++top] = item;//压栈
}

template<class T>//取栈顶元素
T stack<T>::gettop()const{
	assert(!empty());
	return a[top];
}

template<class T>//弹栈
void stack<T>::pop(){
	assert(!empty());
	return a[top--];
}

template<class T>//清除栈
void stack<T>::clear(){
	top = -1;
}

template<class T>//栈显示,从栈顶到栈底
void stack<T>::display(const stack<T> &s1){
	for (int i = cn-1; i >= 0; i--)
		cout << s1.a[i] << " " << endl;
}
#endif
//main函数测试
#include<iostream>
#include"stack.h"
using namespace std;


int main(){
	stack<int>s(3);
	cout << "stack is empty?" << s.empty() << endl;
	s.push(1);
	s.push(2);
	s.push(3);
	cout << "the stack is:" << endl;
	s.display(s);
	cout << "the top is:" << s.gettop() << endl;;
	s.clear();
	stack<char>a(3);
	a.push('x');
	a.push('u');
	a.push('z');
	a.display(a);
	system("pause");
	return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值