#ifndef LISTSTACK_H
#define LISTSTACK_H
#include <iostream.h>
#include <assert.h>
template <class Type> class Stack;
template <class Type>
class StackNode
{
friend class Stack<Type>;
private:
Type data;
StackNode<Type> *link;
StackNode(Type d=0,StackNode<Type> *l=NULL):data(d),link(l){}
};
template <class Type>
class Stack
{
public:
Stack():top(NULL){}
~Stack();
void Push(const Type &item);
Type Pop();
Type GetTop();
void MakeEmpty();
int IsEmpty() const { return top==NULL; }
private:
StackNode<Type> *top;
};
template <class Type>
Stack<Type>::~Stack()
{
MakeEmpty();
}
template <class Type>
void Stack<Type>::Push(const Type &item)
{
top=new StackNode<Type>(item,top);
}
template <class Type>
Type Stack<Type>::Pop()
{
assert(!IsEmpty());
StackNode<Type> *p=top;
Type revalue=p->data;
top=top->link;
delete p;
return revalue;
}
template <class Type>
Type Stack<Type>::GetTop()
{
assert(!IsEmpty());
return top->data;
}
template <class Type>
void Stack<Type>::MakeEmpty()
{
StackNode<Type> *p;
while(top!=NULL)
{
p=top;top=top->link;delete p;
}
}
#endif
#include "liststack.h"
int main()
{
Stack<int> stack;
for(int i=0;i<5;i++)
stack.Push(i*10+5);
for(i=0;i<4;i++)
{
cout<<stack.Pop()<<" ";
cout<<stack.GetTop()<<endl;
}
cout<<endl;
return 1;
}
温馨提示:内容为网友见解,仅供参考