1,链栈的定义:
栈是限定仅在表尾进行插人或删除操作的线性表。因此,对栈来说,表尾端有其特殊含义,称为栈顶,相应地,表头端称为栈底。不含元素的空表称为空栈。栈的修改是按后进先出的原则进行的,因此栈又称为后进先出的线性表,简称LIFO结构。而链栈就是使用链式结构来实现栈,链栈的空间可以是不连续分配。
结构图:
//定义结点
template<class elemtype>
class node
{
public:
elemtype data;
node<elemtype>* next;
};
//定义模板类
template<class elemtype>
class linkstack
{
public:
linkstack();//构造函数,初始化空的链栈
~linkstack();//析构函数,释放链栈中所有结点
void push(elemtype x);//x入栈
void pop();//栈顶元素出栈
elemtype gettop();//取栈顶元素
int empty();//判断链栈是否为空
private:
node<elemtype>* top;//栈顶指针
};
template<class elemtype>
linkstack<elemtype>::linkstack()
{
}
template<class elemtype>
linkstack<elemtype>::~linkstack()
{
while (top != NULL)
{
node<elemtype>* q = top;
top = top->next;
delete q;
}
}
template<class elemtype>
void linkstack<elemtype>::push(elemtype x)
{
node<elemtype>* s = new node<elemtype>;
s->data = x;
s->next = top;
top = s;
}
template<class elemtype>
void linkstack<elemtype>::pop()
{
if (top == NULL)
{
cout << "链栈为空" << endl;
return;
}
node<elemtype>* q = top;
top = top->next;
delete q;
}
template<class elemtype>
elemtype linkstack<elemtype>::gettop()
{
if (top != NULL)
{
return top->data;
}
else
{
cout << "linkstack为空" << endl;
}
}
template<class elemtype>
int linkstack<elemtype>::empty()
{
if (top == NULL)
{
return 1;
}
else
{
return 0;
}
}