c++实现数据结构六 链式栈

StackNode.h

template<typename Type> class LinkStack;

template<typename Type> class StackNode
{
private:
	Type data;
	StackNode<Type> *pnext;
private:
	friend class LinkStack<Type>;
	StackNode() {};
	StackNode(Type item, StackNode<Type> *next=NULL):data(item), pnext(next) {}
	~StackNode()
	{
		cout<<"析构函数"<<endl;
		pnext = NULL;
	}

};


 

LinkNode.h

#include "StackNode.h"

template<typename Type> class LinkStack
{
public:
	LinkStack():ptop(NULL) {}
	~LinkStack()
	{
		cout<<"~LinkStack"<<endl;
		MakeEmpty();
	}
public:
	void MakeEmpty();
	void Push(const Type item);
	Type Pop();
	Type GetTop() const;
	void Print();
	bool IsEmpty() const
	{
		return ptop == NULL;
	}

private:
	StackNode<Type> *ptop;
};

template<typename Type>
void LinkStack<Type>::MakeEmpty()
{
	if( IsEmpty() )
	{
		cout<<"the link stack has been empty"<<endl;
		exit(1);
	}
	StackNode<Type> *pdel;
	while(ptop != NULL)
	{
		pdel =ptop;
		ptop = ptop->pnext;
		delete pdel;
	}
}

template<typename Type>
void LinkStack<Type>::Push(const Type item)
{
	StackNode<Type> *ele = new StackNode<Type>;
	ele->data = item;
	ele->pnext= ptop;
	ptop = ele;
	//ptop = new StackNode<Type>(item, ptop);
}

template<typename Type>
Type LinkStack<Type>::Pop()
{
	if( IsEmpty())
	{
		cout<<"cannot pop the stack node"<<endl;
		exit(1);
	}
	StackNode<Type> *pdel =ptop;
	ptop=ptop->pnext;
	Type item = pdel->data;
	delete pdel;
	return item;
}

template<typename Type>
Type LinkStack<Type>::GetTop() const
{
	if( IsEmpty() )
	{
		cout<<"the link stack is empty"<<endl;
		exit(1);
	}

	return ptop->data;
}

template<typename Type>
void LinkStack<Type>::Print()
{
	cout<<"top";
	StackNode<Type> *pmov=ptop;
	while(pmov != NULL)
	{
		cout<<"-->"<<pmov->data;
		pmov = pmov->pnext;
	}
	cout<<"-->buttom"<<endl;
}


 

顺便测试了下析构函数,只有在对象释放时才会调用析构函数。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值