#include<iostream>
using namespace std;
template<typename T>
class Stack
{
public:
Stack(int s=10);
~Stack();
bool StackEmpty();
int StackLength();
T GetTop(T &e);
void Push(T e);
T Pop(T &e);
private:
T *base;
T *top;
int stacksize,count;
T *array;
};
template<typename T>
Stack<T>::Stack(int s=10)
{
array=new T[s];
stacksize=s;
count=0;
top=base=array;
}
template<typename T>
Stack<T>::~Stack()
{
}
template<typename T>
bool Stack<T>::StackEmpty()
{
return count==0;
}
template<typename T>
int Stack<T>::StackLength()
{
return count;
}
template<typename T>
T Stack<T>::GetTop(T &e)
{
e=*(top-1);
return e;
}
template<typename T>
void Stack<T>::Push(T e)
{
if(count+1<=stacksize)
{
count++;
*top=e;
top++;
}
else
{
cout<<"栈空间不足"<<endl;
}
}
template<typename T>
T Stack<T>::Pop(T &e)
{
if(count==0)
cout<<"栈已经为空"<<endl;
else
{
e=*(top-1);
top--;
count--;
}
return e;
}
int main()
{
Stack<int> a1(9);
for(int i=0;i<10;i++)
a1.Push(i);
cout<<"栈的大小:"<<a1.StackLength()<<endl;
cout<<"栈是否为空:"<<a1.StackEmpty()<<endl;
int e;
cout<<"栈顶元素:"<<a1.GetTop(e)<<endl;
while(!a1.StackEmpty())
{
int e;
cout<<a1.Pop(e)<<endl;
}
return 0;
}
C++数据结构栈的实现
最新推荐文章于 2021-11-17 14:44:39 发布