/*************************************顺序栈存储结构及常见操作************************************/
#ifndef _seqstack_h
#define _seqstack_h
#include <stdlib.h>//基本库函数
#include <stdio.h>
#define STACKMINSIZE 10//顺序栈存储空间长度的最小值
typedef int StackDT;
class SeqStack //顺序栈存储结构类型定义
{public:
StackDT* base;
int stacksize;
int top;
void StackInitialize(SeqStack ps,int nsize);//初始化
int StackLen(SeqStack s);//求栈长度
bool StackEmpty(SeqStack s);//判断栈是否为空
bool StackFull(SeqStack s);//判断栈是否为满
bool push(SeqStack ps,StackDT d);//入栈
bool pop(SeqStack ps,StackDT pd);//出栈
bool StackGetTop(SeqStack s,StackDT pd);//获取栈顶元素
bool StackPutTop(SeqStack s,StackDT d);//写栈顶元素
void StackClear(SeqStack ps);//清空栈
void StackDestroy(SeqStack s);//销毁栈
};
void SeqStack::StackInitialize(SeqStack ps,int nsize)//初始化
{
if (nsize<STACKMINSIZE)
nsize=STACKMINSIZE;
ps.stacksize=nsize;
ps.base=(StackDT*)malloc(ps.stacksize*sizeof(StackDT));
if (!ps.base)
exit(EXIT_FAILURE);
ps.top=-1;
}
int SeqStack::StackLen(SeqStack s)//求栈长度
{
return s.top+1;
}
bool SeqStack::StackEmpty(SeqStack s)//判断栈是否为空
{
return -1==s.top?true:false;
}
bool SeqStack::StackFull(SeqStack s)//判断栈是否为满
{
return s.stacksize-1<=s.top?true:false;
}
bool SeqStack::push(SeqStack ps,StackDT d)//入栈
{
bool flg=true;
if (StackFull(ps))
{flg=false;
}
else
{ps.base[++ps.top]=d;
}
return flg;
}
bool SeqStack::pop(SeqStack ps,StackDT pd)//出栈
{
bool flg=true;
if (StackEmpty(ps))
{flg=false;
}
else
{pd=ps.base[ps.top--];
}
return flg;
}
bool SeqStack::StackGetTop(SeqStack s,StackDT pd)//获取栈顶元素
{ bool flg=true;
if (StackEmpty(s))
{flg=false;
}
else
{pd=s.base[s.top];
}
return flg;
}
bool SeqStack::StackPutTop(SeqStack s,StackDT d)//写栈顶元素
{
bool flg=true;
if (StackEmpty(s))
{flg=false;
}
else
{s.base[s.top]=d;
}
return flg;
}
void SeqStack::StackClear(SeqStack ps)//清空栈
{
ps.top=-1;
}
void SeqStack::StackDestroy(SeqStack s)//销毁栈
{
free(s.base);
}
#define N 10
void main()
{int i;
StackDT d,a[N]={0,1,2,3,4,5,6,7,8,9};
SeqStack stack;
stack.StackInitialize(stack,N);
printf("/npush:/n");
for(i=0;i<N;i++)
{
printf("%3d",a[i]);
stack.push(stack,a[i]);
}
printf("/nstack is %s",stack.StackFull(stack)? "full":"not full");
printf("stacklen=%d",stack.StackLen(stack));
printf("/npop:/n");
while (!stack.StackEmpty(stack))
{stack.pop(stack,d);
printf("%3d",d);
}
printf("/nstack is %s/n",stack.StackEmpty(stack)?"empty":"not empty");
stack.StackDestroy(stack);
}
#endif