酱油,简单实现stack

大笑看了下C++ primer中的类模板后顺手写的。。

(未实现复制构造) 功能少,可能还会有错误,哈哈。


代码:

#include <iostream>
template<class type>
class Data
{
public:
	type data;
	Data *next;
};
template<class type>
class stack
{
public:
	stack():sz(0),head(NULL) {}
	stack(type x):sz(0),head(NULL) {push(x);}
	stack(int n,type x);
	type size() {return sz;}
	type is_empty() {return sz==0;}
	void push(type a);
	void pop();
	type& top();
	void list_all();
	void destroy();
	~stack() {destroy();}
private:
	Data<type> *head;
	unsigned int sz;
};
template<class type>type& stack<type>::top()
{
	if(!is_empty())
		return head->data ;
	std::cout<<"空栈"<<std::endl;
	exit(1);
}
template<class type>void stack<type>::list_all()
{
	Data<type> *p=this->head;
	while(p)
	{
		std::cout<<p->data << " ";
		p=p->next ;
	}
	std::cout<<std::endl;
}
template<class type>std::ostream& operator<<(std::ostream& out,stack<type>& t)
{
	out<<t.top();
	return out;
}
template<class type>stack<type>::stack(int n,type x):sz(0),head(NULL)
{
	for(int i=0;i<n;++i) push(x);
}
template<class type>void stack<type>::push(type a)
{
	Data<type> *p=new Data<type>;
	p->data =a;
	p->next =NULL;
	if(is_empty())
		head=p;
	else
	{
		p->next =head;
		head=p;
	}
	++sz;
}
template<class type>void stack<type>::pop()
{
	if(!is_empty())
	{
		Data<type> *p=head;
		head=head->next ;
		delete p;
		--sz;
		std::cout<<"data left:"<<size()<<std::endl;
	}
	else
	{
		std::cout<<"空栈"<<std::endl;
	}
}
template<class type>void stack<type>::destroy()
{
	while(!is_empty()) pop();
}


void test()
{
	stack<double >a;
	for(int i=0;i<5;++i)
		a.push (i*0.1);
	a.list_all();
	while(!a.is_empty ())
	{
		std::cout<<a<<std::endl;
		a.pop();
	}
}
int main()
{
	test();
}


运行截图:


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值