# include <stdio.h>
# include <stdlib.h>
# define StackSize 100
/**
* 时间:2016年6月10日 00:10:41
* 内容:顺序栈
*/
typedef char DataType;
typedef struct
{
DataType stack[StackSize];
int top;
}SeqStack;
void InitStack(SeqStack*);
int StackEmpty(SeqStack*);
int GetTop(SeqStack*,DataType*);
int PushStack(SeqStack*,DataType);
int PopStack(SeqStack*,DataType*);
int StackLength(SeqStack*);
void ClearStack(SeqStack*);
int main(void)
{
SeqStack S;
int i;
DataType a[]={'a','b','c','d','e','f'};
DataType e;
InitStack(&S);
for (i=0;i<sizeof(a)/sizeof(a[0]);i++)
{
if (PushStack(&S,a[i])==0)
{
printf("栈已满,不能进栈!\n");
return 0;
}
}
printf("出栈的元素!\n");
if (PopStack(&S,&e)==1)
printf("出栈成功!%4c\n",e);
printf("当前栈顶元素是:");
if (GetTop(&S,&e)==1)
printf("%4c\n", e);
if (PushStack(&S,'g')==0)
printf("栈已满,不能进栈!\n");
printf("栈的长度:%d\n",StackLength(&S));
ClearStack(&S);
if (GetTop(&S,&e)==0)
printf("栈已经为空!\n");
return 0;
}
/**
* 将栈初始化为空栈
* @param S 栈
*/
void InitStack(SeqStack *S)
{
S->top=0;// 把栈顶指针置0
}
/**
* 判读是否为空
* @param S 栈
* @return 返回是否为空,1不为空,0为空
*/
int StackEmpty(SeqStack *S)
{
if (S->top==0)
return 1;
else
return 0;
}
/**
* 读取栈顶元素
* @param S 栈
* @param e 接收取回的数据类型
* @return 是否为空,1不为空,0为空
*/
int GetTop(SeqStack *S,DataType *e)
{
if (S->top<=0)
{
printf("栈已经为空!\n");
return 0;
}
else
{
*e=S->stack[S->top-1];
return 1;
}
}
/**
* 进栈,将元素e进栈
* @param S 栈
* @param e 元素
* @return 返回是否成功进栈,1为真,0为假
*/
int PushStack(SeqStack *S,DataType e)
{
if (S->top>=StackSize)
{
printf("栈已经满了,不能进栈了!\n");
return 0;
}
else
{
S->stack[S->top]=e;
S->top++;
return 1;
}
}
/**
* 出栈操作,将栈顶元素出栈,并将值赋给e
* @param S 栈
* @param e 元素
* @return 返回是否成功出栈,1为真,0为假
*/
int PopStack(SeqStack *S,DataType *e)
{
if (S->top<=0)
{
printf("已是空栈,不能出栈!\n");
return 0;
}
else
{
*e=S->stack[S->top];
return 1;
}
}
/**
* 返回栈的长度
* @param S 栈
* @return 返回是否成功
*/
int StackLength(SeqStack *S)
{
return S->top;
}
/**
* 清除栈
* @param S 栈
* @return 返回是否成功
*/
void ClearStack(SeqStack *S)
{
S->top=0;//这种删除的方法不彻底,可以通过改变top的值找回原来的值
}
顺序栈
最新推荐文章于 2025-03-19 06:06:30 发布