#include"stdafx.h"
#include<iostream>
usingnamespacestd;
template<classT>
classListNode //节点类
{
public:
typedefListNode<T>*pListNode;
typedefListNode<T>&rListNode;
public:
ListNode<T>*Next;
Tval;
public:
ListNode(constT&value,pListNodep=NULL):val(value),Next(p){};
ListNode():Next(NULL){};
~ListNode(){};
};
template<classT>
classstack
{
public:
typedefListNode<T>*pNode;
protected:
pNodepTop; //定义头指针
public:
stack():pTop(NULL){}
~stack(){deleteAllNode();}
voiddeleteAllNode()
{
while(!isEmpty())pop();
}
boolisEmpty()const
{
return(pTop==NULL);
}
//boolisFull(){return false;} //此时是利用链表内存基本无限(硬件支持)
constT&getTop()const
{
returnpTop->val;
}
voidpush(constT&data)
{
pTop= newListNode<T>(data,pTop);
}
voidpop()
{
if(pTop== NULL) //首先判断
return;
pNodeq= pTop;
pTop= pTop->Next;
deleteq;
}
conststack&operator=(conststack&src);
};
template<classT>
conststack<T>&stack<T>::operator=(conststack&src) //赋值
{
if(this==&src|| src.isEmpty())return*this;
deleteAllNode();
pListNode*p= newListNode<T>(src.pTop->val);
pListNode*q= src.pTop->Next;
pTop= p;
while(q!= NULL)
{
p->Next= newListNode<T>(q->val);
p= p->Next;
q= q->Next;
}
return*this;
}
intmain()
{
stack<int>p;
p.push(1);
p.push(2);
p.push(3);
p.push(4);
intval= p.getTop();
cout<<val<<endl;
for(inti=0;i<3;i++)
{
p.pop();
val= p.getTop();
cout<<val<<endl;
}
getchar();
return0;
}