C++模板实现链式栈

      链式栈是一种数据存储结构,可以通过单链表的方式来实现,使用链式栈的优点在于它能够克服用数组实现的顺序栈空间利用率不高的特点,但是需要为每个栈元素分配额外的指针空间用来存放指针域。

     下面我们使用模板实现一个简单链式栈:

StackNode.h

template class LinkStack;

template class StackNode{
private:
	friend class LinkStack;
	StackNode(Type dt,StackNode *next=NULL):m_data(dt),m_pnext(next){} 

private:
	Type m_data;
	StackNode *m_pnext;
};
LinkStack.h

#include "StackNode.h"

template class LinkStack{
public:
	LinkStack():m_ptop(NULL){}
	~LinkStack(){
		MakeEmpty();
	}

public:
	void MakeEmpty();           //make the stack empty
	void Push(const Type item); //push the data
	Type Pop();                 //pop the data
	Type GetTop() const;        //get the data
    void Print();               //print the stack
        
	bool IsEmpty() const{
		return m_ptop==NULL;
	}
	
private:
	StackNode *m_ptop;
};

template void LinkStack::MakeEmpty(){
	StackNode *pmove;
	while(m_ptop!=NULL){
		pmove=m_ptop;
		m_ptop=m_ptop->m_pnext;
		delete pmove;
	}
}

template void LinkStack::Push(const Type item){
	m_ptop=new StackNode(item,m_ptop);
}

template Type LinkStack::GetTop() const{
	if(IsEmpty()){
		cout<<"There is no elements!"<m_data;
}

template Type LinkStack::Pop(){
	if(IsEmpty()){
		cout<<"There is no elements!"< *pdel=m_ptop;
	m_ptop=m_ptop->m_pnext;
	Type temp=pdel->m_data;
	delete pdel;
	return temp;
}

template void LinkStack::Print(){
	StackNode *pmove=m_ptop;
	cout<<"buttom";
	while(pmove!=NULL){
		cout<<"--->"<m_data;
		pmove=pmove->m_pnext;
	}
	cout<<"--->top"<
Main.cpp

#include 
using namespace std;

#include "LinkStack.h"

int main(){
	LinkStack stack;
	int init[10]={1,3,5,7,4,2,8,0,6,9};
	for(int i=0;i<10;i++){
		stack.Push(init[i]);
	}
	stack.Print();

	cout<






你可能感兴趣的:(C++,数据结构,C/C++/C#开发实战365)