LinkedStack.h头文件源代码:
#ifndef
LINKEEDSTACK_H
#define
LINKEEDSTACK_H
template
class
LinkedStack;
template
class
ChainNode
{
friend
class LinkedStack;
private:
ChainNode(const
T& theData,ChainNode* n=NULL)
:data(theData),link(n){}
T
data;
ChainNode*
link;
};
template
class
LinkedStack
{
public:
LinkedStack():top(0){} //构造函数
~LinkedStack(){MakeEmpty();} //析构函数
bool
IsEmpty()
const; //判断堆栈是否为空的成员函数
T&
Top()
const; //返回栈顶数据
void
Push(const T&
e); //向栈中压入数据
void
Pop(); //删除栈顶元素
void
MakeEmpty(); //清空栈
private:
ChainNode*
top; //栈顶指针
};
template
bool
LinkedStack::IsEmpty() const
{
return
top==NULL;
}
template
void LinkedStack::Push(const T&
e) //插入数据
{
top=new
ChainNode(e,top); //将原来的栈顶指针给新节点的link,新节点的指针成为栈顶指针
}
template
T&
LinkedStack::Top() const
{
if(this->IsEmpty())
throw
"Stack is empty.";
return
top->data;
}
template
void
LinkedStack::Pop()
{
if(this->IsEmpty())
throw
"Stack is empty.Cannot delete.";
ChainNode*
delNode=top;
top=top->link;
delete
delNode;
}
template
void
LinkedStack::MakeEmpty()
{
while(!IsEmpty())
Pop();
}
#endif
主程序源代码:
#include
#include"LinkedStack.h"
using
namespace std;
int
main()
{
LinkedStack
s;
s.Push(10);
cout<<s.Top()<<endl;
s.Push(20);
cout<<s.Top()<<endl;
s.Push(30);
cout<<s.Top()<<endl;
s.Pop();
cout<<s.Top()<<endl;
return
0;
}
运行结果: