栈,后进先出,应用广泛(后面树的非递归遍历等)。(所使用的是CPP文件)
目录
预先要引用的头文件以及宏定义
#include<stdio.h>
#include<iostream>
using namespace std;
#define TRUE 1
#define FALSE 0
#define OK 1
#define ERROR 0
#define OVERFLOW -1
typedef int ElemType;
typedef int Status;
所使用栈的结构(其实多差不多,看你需求)
typedef struct
{
ElemType* elem;//存储空间基址
int top;//栈顶元素的下一个位置,简称栈顶位标
int size;//当前分配的存储容量
int increment;//扩容时,增加的存储容量
}SqStack;
其基本操作接口
Status InitStack_Sq(SqStack& S, int size, int inc);//初始化顺序栈
Status DestroyStack_Sq(SqStack& S); //销毁顺序栈
Status StackEmpty_Sq(SqStack S); //判断栈是否为空,空返回TRUE,否则返回FALSE
void ClearStack_Sq(SqStack& S); //清空栈
Status Push_Sq(SqStack& S, ElemType e); //元素e压入栈
Status Pop_Sq(SqStack& S, ElemType &e); //栈S的栈顶元素出栈并用e返回
Status GetTop_Sq(SqStack S, ElemType& e); //取栈S的栈顶元素,并用e返回
初始化顺序栈
Status InitStack_Sq(SqStack& S, int size, int inc)
{
S.elem = (ElemType*)malloc(size * sizeof(ElemType));
if (S.elem == NULL)
{
return OVERFLOW;
}
else
{
S.top = 0;
S.size = size;
S.increment = inc;
return OK;
}
}
销毁顺序栈
Status DestroyStack_Sq(SqStack& S)
{
free(S.elem);
S.increment = 0;
S.size = 0;
S.top = 0;
return OK;
}
判断栈是否为空,空返回TRUE,否则返回FALSE
Status StackEmpty_Sq(SqStack S)
{
if (S.top == 0)
{
return TRUE;
}
else
{
return FALSE;
}
}
清空栈
void ClearStack_Sq(SqStack& S)
{
S.top = 0;
}
元素e压入栈
Status Push_Sq(SqStack& S, ElemType e)
{
ElemType* newbase;
if (S.top >= S.size)
{
newbase = (ElemType*)realloc(S.elem, (S.size + S.increment) * sizeof(ElemType));
if (newbase == NULL)
{
return OVERFLOW;
}
S.elem = newbase;
S.size = S.size + S.increment;
}
S.elem[S.top] = e;
S.top++;
return OK;
}
栈S的栈顶元素出栈并用e返回
Status Pop_Sq(SqStack& S, ElemType& e)
{
if (S.top == 0)
{
return ERROR;
}
else
{
S.top = S.top - 1;// --S.top;
e = S.elem[S.top];
return OK;
}
}
取栈S的栈顶元素,并用e返回
Status GetTop_Sq(SqStack S, ElemType& e)
{
if (S.top == 0)
{
return ERROR;
}
else
{
e = S.elem[S.top - 1];
}
}
一些接口的测试
int main()
{
SqStack S;
InitStack_Sq(S,5,5);//初始化栈
int k = 0;
for (int i = 0; i < 7; i++)//入栈
{
Push_Sq(S, k);
k++;
}
cout << S.increment<<endl;
cout << S.top<<endl;
cout << S.size<<endl;
ElemType e;
GetTop_Sq(S, e);//取得栈顶元素
cout << S.elem[S.top - 1] << endl;
for (int i = 0; i < S.top; i++)
{
cout << S.elem[i];
}
cout << "\n";
for (int i = 0; i < 3; i++)//出栈
{
ElemType e1;
Pop_Sq(S, e1);
cout << e1;
}
cout << "\n";
cout << S.increment << endl;
cout << S.top << endl;
cout << S.size << endl;
}
如有错误,请指正。