#ifndef LINKEDSTACK_H
#define LINKEDSTACK_H
#include <iostream>
#include <assert.h>
using namespace std;
template<class T>
struct LinkNode //链栈节点类的定义
{
T data; //数据域
LinkNode<T> *link; //链指针域
LinkNode(LinkNode<T> *ptr = NULL) //仅初始化指针成员的构造函数
{
link = ptr;
}
LinkNode(const T &item,LinkNode<T> *ptr = NULL) //初始化数据与指针成员的构造函数
{
data = item;
link = ptr;
}
};
template<class T>
class LinkedStack
{
public:
LinkedStack():top(NULL){}
~LinkedStack()
{
MakeEmpty();
}
void Push(const T &x); //进栈
bool Pop(T &x); //出栈
bool GetTop(T &x)const; //读取栈顶元素
bool IsEmpty()const //判断栈空否
{
return (top == NULL) ? true : false;
}
int GetSize()const; //求栈的元素个数
void MakeEmpty(); //清空栈的内容
template<class T>
friend ostream& operator<<(ostream& os,LinkedStack<T>& s);
private:
LinkNode<T> *top; //栈顶指针
};
template<class T>
void LinkedStack<T>::MakeEmpty()
{
LinkNode<T> *p;
while (top != NULL)
{
p = top;
top = top->link;
delete p;
}
}
template<class T>
void LinkedStack<T>::Push(const T &x)
{
top = new LinkNode<T>(x,top);
assert(top != NULL);
}
template<class T>
bool LinkedStack<T>::Pop(T &x)
{
if(IsEmpty() == true)
return false;
LinkNode<T> *p = top;
top = top->link;
x = p->data;
delete p;
return true;
}
template<class T>
bool LinkedStack<T>::GetTop(T &x)const
{
if(IsEmpty() == true)
return false;
x = top->data;
return true;
}
template<class T>
int LinkedStack<T>::GetSize()const
{
LinkNode<T> *p = top;
int count = 0;
while (p != NULL)
{
++count;
p = p->link;
}
return count;
}
template<class T>
ostream& operator<<(ostream& os,LinkedStack<T>& s)
{
os<<"栈中的元素个数="<<s.GetSize()<<endl;
LinkNode<T> *p = s.top;
int i = 0;
while (p != NULL)
{
os<<++i<<":"<<p->data<<endl;
p = p->link;
}
return os;
}
#endif