C语言利用模板实现简单的栈类语言利用模板实现简单的栈类
本文实例为大家分享了C语言利用模板实现简单的栈类(数组和单链表),供大家参考,具体内容如下
主要的功能是实现一个后进先出的列表,有入栈、出栈、返回大小、判空等基本功能
#pragma once
using namespace std;
const int MAXSIZE = 0xfff;
template<class type>
class Class_Linkstack
{
int top;
type* my_s;
int max_size;
public:
Class_Linkstack() :top(-1), max_size(MAXSIZE)
{
my_s = new type[max_size];
if (my_s == NULL)
{
cerr << "动态存储分配失败!" << endl;
exit(1);
}
}
Class_Linkstack(int size) :top(-1), max_size(size)
{
my_s = new type[size];
if (my_s == NULL)
{
cerr << "动态存储分配失败!" << endl;
exit(1);
}
}
~Class_Linkstack() { delete[] my_s; }
bool Empty_Linkstack();
void Push_Linkstack(type tp);
void Pop_Linkstack();
type Top_Linkstack();
int Size_Linkstack();
void Print_Linkstack();
};
template<class type>
void Class_Linkstack<type>::Print_Linkstack()
{
if (top == -1)
cout << "空栈" << endl;
else
{
for (int i = 0; i < top+1; i++)
cout << my_s[i] << ' ';
}
}
template<class type>
bool Class_Linkstack<type>::Empty_Linkstack()
{
if (top == -1)
return true;
else
{
return false;
}
}
template<class type>
void Class_Linkstack<type>::Push_Linkstack(type tp)
{
if (top + 1 < max_size)
my_s[++top] = tp;
else
{
cout << "栈已满" << endl;