Template Stack

本文介绍了一个通用模板栈类的实现方法,并通过实例演示了如何使用该栈类进行数据的存储与操作。栈类支持多种基本操作,如压栈、出栈、查看栈顶元素等,并展示了栈在数据转移及存储管理中的应用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

#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();//输出空
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值