- 栈(stack): 限定仅在表尾进行插入或删除操作的线性表。表尾称为栈顶(top),表头称为栈底(bottom)。
- 栈的特点: 先进后出。
- 顺序栈: 使用一组地址连续的存储单元依次存放自栈底到栈顶的数据元素。
顺序栈需要牺牲一个地址空间来存放Top指针,即栈顶指针在栈顶元素的下一个位置上。
栈空的判定条件:SqStack.base=SqStack.Top
栈不存在的判定条件:SqStack.base=NULL
#include <iostream>
#include <cstdio>
#include <malloc.h>
#define STACK_INIT_SIZE 100
#define STACK_INCREMENT 10
typedef int SElemType;
typedef bool Status;
using namespace std;
typedef struct
{
SElemType *base;
SElemType *top;
int stackSize;
}SqStack;
///创建Stack
Status CreateSqStack_S(SqStack &S)
{
S.base=(SElemType*)malloc(STACK_INIT_SIZE*sizeof(SElemType));
if(!S.base)
return false;
S.top=S.base;
S.stackSize=STACK_INIT_SIZE;
return true;
}
///压栈
Status PushSqStack_S(SqStack &S,SElemType e)
{
if(S.top-S.base>=S.stackSize)
{
S.base=(SElemType*)realloc(S.base,(S.stackSize+STACK_INCREMENT)*sizeof(SElemType));
if(!S.base)
return false;
S.top=S.base+S.stackSize;
S.stackSize=S.stackSize+STACK_INCREMENT;
}
*S.top++=e;
return true;
}
///出栈
void PopSqStack_S(SqStack &S,SElemType &e)
{
if(S.base==S.top)
printf("The stack is NULL!\n");
else
{
e=*(--S.top);
}
}
///get栈顶元素
void GetTopSqStack_S(SqStack S,SElemType &e)
{
if(S.base==NULL)
printf("The stack S is not exist!\n");
else if(S.base==S.top)
printf("The stack is NULL!\n");
else
{
e=*(S.top-1);
printf("The element of top:%d\n",e);
}
}
///将栈清空
void ClearSqStack_S(SqStack &S)
{
if(S.top!=S.base)
S.top=S.base;
}
///销毁栈
void DeleteSqStack_S(SqStack &S)
{
// for(int i=S.stackSize-1;i>=0;i--)
// {
// SElemType *tempAdd=S.base+i;
// free(tempAdd);
// tempAdd=NULL;
// }
free(S.base);
S.base=NULL;
S.top=NULL;
S.stackSize=0;
}
int main()
{
SqStack stack1;
CreateSqStack_S(stack1);
SElemType e;
PushSqStack_S(stack1,5);
PushSqStack_S(stack1,3);
GetTopSqStack_S(stack1,e);
// PopSqStack_S(stack1,e);
// PopSqStack_S(stack1,e);
//ClearSqStack_S(stack1);
DeleteSqStack_S(stack1);
//printf("OK!\n");
GetTopSqStack_S(stack1,e);
return 0;
}
参考:《数据结构C语言版》(严蔚敏)