#include <iostream>
#define MAXSIZE 10
using namespace std;
template <typename T>
class Stack
{
private:
T value;//栈值
T* base;
T top;//栈顶
int maxsize;//顺序栈的最大容量、
public:
Stack();
~Stack();
//判断栈是否为空
bool empty();
//判断栈是否为满
bool full();
//弹栈
bool pop();
//压栈
bool push(int value);
//遍历
void show();
//计算栈的长度
int stacklenth();
};
//构造函数
template <typename T>
Stack<T>::Stack()
{
base =new T[MAXSIZE];
top = 0;
}
//析构函数
template <typename T>
Stack<T>::~Stack<T>()
{
delete[]base;
base = nullptr;
cout<<"析构函数"<<endl;
}
//判断栈是否为满的实现
template<typename T>
bool Stack<T>::full(){
return top == MAXSIZE;
}
//判断栈是否为空的实现
template<typename T>
bool Stack<T>::empty() {
return top == 0;
}
//弹栈
template <typename T>
bool Stack<T>::pop()
{
if(empty())
{
return false;
}
top--;
return true;
}
//压栈
template<typename T>
bool Stack<T>::push(int value) {
if (full()) {
cout << "栈已经满了,无法继续添加元素" << endl;
return false;
}
base[top] = value;
top++;
cout << "值压入成功!" << endl;
return true;
}
//遍历
template <typename T>
void Stack<T>::show()
{
for(int i = top-1;i>=0;i--)
{
cout<<base[i]<<endl;
}
}
//计算栈的长度
template <typename T>
int Stack<T>::stacklenth()
{
return top;
}
int main()
{
Stack <int> s;
s.push(7);
s.push(5);
s.push(5);
s.push(57);
s.push(81);
s.show();
s.pop();
s.pop();
s.show();
return 0;
}
用模板类函数实现顺序栈的功能
最新推荐文章于 2024-10-08 00:02:21 发布