#include<iostream>
#include<assert.h>
using namespace std;
template <class T1,int Size = 10>
class Stack
{
public:
Stack()
{
top = -1;
}//初始化栈
void push(const T1 &item)
{
assert(!isfull());
++top;
list[top] = item;
}//将item压入栈
T1 pop()
{
assert(!isempty());
top--;
return list[top];
}//出栈
void clear()
{
top = -1;
}//清空栈
const T1 &peek() const
{
int temp = list[top];
return list[top];
}//访问栈顶元素
bool isfull() const
{
return top == Size-1 ? true : false;
}//判断栈满
bool isempty() const
{
return top == -1 ? true : false;
}//判断栈空
void print()
{
for(int i = top;i>=0;i--)
{
cout<<list[i]<<endl;
}
}
private:
T1 list[Size];
int top;
};
void main()
{
Stack<int> a;
Stack<int> b;
a.push(1);
a.push(2);
a.push(3);
a.push(4);
a.push(5);
a.print();
cout<<endl;
while(!a.isempty())
{
b.push(a.peek());
a.pop();
}
b.print();
cout<<endl;
while(!b.isempty())
{
b.pop();
}
b.print();
cout<<endl;
Stack<int> S;
S.push(2);
S.push(3);
S.push(4);
S.print();//输出4 3 2
cout<<endl;
S.pop();
S.print();//输出3 2
cout<<endl;
S.isempty();
if(!S.isempty())
cout<<"栈不空"<<endl;
else
cout<<"栈空"<<endl;
S.isfull();
if(!S.isfull())
cout<<"栈不满"<<endl;
else
cout<<"栈满"<<endl;
cout<<endl;
S.clear();
S.print();//输出空
}
Template Stack
最新推荐文章于 2021-06-14 20:37:57 发布