自己实现栈结构
#include<iostream>
#include<assert.h>
using namespace std;
template<class T> class Stack;
template<class T> class StackNode{
friend class Stack<T>;
private:
T data;
StackNode<T> *link;
StackNode(T d = 0,StackNode<T>* l=NULL):data(d),link(l){}
};
template<class T> class Stack{
public:
Stack():top(NULL){}
~Stack();
void Push(const T& item);
T Pop();
T GetTop();
void MakeEmpty();
int IsEmpty()const {
return top == NULL;
}
private:
StackNode<T> *top;//栈顶指针
};
template<class T> Stack<T>::~Stack(){
StackNode<T> *p;
while(top!=NULL){
p=top;
top=top->link;//逐节点回收
delete p;
}
}
template <class T> void Stack<T>::Push(const T& item){
top = new StackNode<T>(item,top);
//新结点链入top之前,并成为新栈顶
}
template <class T> T Stack<T>::Pop(){
assert(!IsEmpty());//判断栈是否为空,若为空,程序中止执行
StackNode<T> *p = top;
T retvalue = p->data;
top = top->link;
delete p;
return retvalue;
}
template <class T> T Stack<T>::GetTop(){
assert(!IsEmpty());
return top->data;
}
int main(){
Stack<int> s;
s.Push(2);
s.Push(3);
s.Push(4);
for(int i=0;i<3;i++){
cout<<s.Pop()<<endl;
}
return 0;
}