栈的定义
栈也是线性表,只不过时限制了删除和插入的位置
栈的特点是后进先出,通常是在表尾进行插入删除。
抽象数据定义
InitStack 初始化栈
DestoryStack 销毁栈
Stacklength 返回栈的长度
Push 压入栈
Pop 出栈
GetTop 返回栈顶
StackEmpty 判断栈是否为空
clearStack() 清空栈
功能不一一实现了
C++代码实现
stack.h 头文件编写
#ifndef STACK_H_
#define STACK_H_
#include<cstdlib>
template<class T>
class Stack
{
private:
enum{MAX = 5};
T *top;
T *base;
int stacksize;
public:
Stack();
bool IsEmpty();
bool StackPush(T e);
T StackPop(T &e);
};
template<class T>
Stack<T>::Stack()
{
this->base = new T[MAX];
if(!this->base)
exit(0);
this->top = this->base;
this->stacksize = MAX;
}
template<class T>
bool Stack<T>::IsEmpty()
{
if(base == top)
return true;
else
return false;
}
template<class T>
bool Stack<T>::StackPush(T e)
{
if(this->top - this->base == stacksize)
return false;
*this->top = e;
this->top++;
return true;
}
template<class T>
T Stack<T>::StackPop(T &e)
{
if(top == base)
exit(0);
this->top--;
e = *top;
return e;
}
#endif
main函数实现
#include"stack.h"
#include<iostream>
using namespace std;
const int MAX = 5;
int main()
{
Stack<int> s;
int x;
for(int i = 0;i < MAX;i++)
{
cin >> x;
s.StackPush(x);
}
for(int i = 0;i < MAX;i++)
{
int e;
s.StackPop(e);
cout << e <<" ";
}
cout << endl;
return 0;
}