#pragma once
#ifndef My_Head_H
#define My_Head_H
#include "G://code/c++/myhead.h"
#endif // !My_Head_H
template <typename ElemType>
class LinkStack
{
public:
class Stack_Node
{
public:
ElemType data;
Stack_Node *next;
};
typedef Stack_Node* Nodepointer;
//把栈置空
void clear();
//求栈中结点个数
int Get_Length();
//弹出栈顶结点
Status Pop(ElemType& e);
//压入数据为e的结点
void Push(ElemType e);
//以随机数填充i个结点
void Random_Fill_Stack(int i);
//打印所有节点
void Display_Stack();
//链栈构造函数
LinkStack();
//链栈析构函数
virtual ~LinkStack();
protected:
Nodepointer top;
};
template<typename ElemType>
void LinkStack<ElemType>::clear()
{
Nodepointer s;
while (top)
{
s = top;
top = top->next;
delete s;
}
top = NULL;
}
template<typename ElemType>
int LinkStack<ElemType>::Get_Length()
{
Nodepointer s;
int count = 0;
s = top;
while (s)
{
count++;
s = s->next;
}
return count;
}
template<typename ElemType>
Status LinkStack<ElemType>::Pop(ElemType& e)
{
Nodepointer s = top;
if (!top) return ERROR;
e = top->data;
top = top->next;
delete s;
return OK;
}
template<typename ElemType>
void LinkStack<ElemType>::Push(ElemType e)
{
Nodepointer s;
s = new Stack_Node;
s->data = e;
s->next = top;
top = s;
}
template<typename ElemType>
void LinkStack<ElemType>::Random_Fill_Stack(int i)
{
for (int count = 0; count < i; count++)
{
Push(random(100));
}
}
template<typename ElemType>
void LinkStack<ElemType>::Display_Stack()
{
Nodepointer s = top;
cout << "Here is all Stack Data:" << endl;
while (s)
{
cout << "->" << s->data;
s = s->next;
}
cout << endl;
return;
}
template<typename ElemType>
LinkStack<ElemType>::LinkStack()
{
top = NULL;
}
template<typename ElemType>
LinkStack<ElemType>::~LinkStack()
{
clear();
}
myhead.h在另一篇博文里:https://blog.csdn.net/cwdben/article/details/105906918