数据结构之顺序栈

#include<stdio.h>

#define MaxSize 5
#define ElemType int

typedef struct {
ElemType data[MaxSize];
int top;
}SqStack;

//初始化
void initStack(SqStack *S)
{
S->top=-1;
}
//判断是否是空栈
int StackEmpty(SqStack *S)
{
if(S->top==-1)return 1;
else{return 0;}
}

//数据压入,先判断是否满
int Push(SqStack *S,ElemType target)
{
if(S->top==MaxSize-1)
{
printf("栈满\n");
return 0;
}

S->data[++S->top]=target;
return 1;
}


//数据弹出,先判断是否空
int Pop(SqStack *S,ElemType *target)
{
if(S->top==-1)
{
printf("空栈\n");
return 0;
}
else{
*target=S->data[S->top];
S->top--;
return 1;
}
}

//读栈顶元素,利用指针将数据传出,返回的是是否读取成功
int read_top(SqStack *S,ElemType *target)
{
if(S->top==-1)
{
printf("空栈\n");
return 0;
}
else{
*target=S->data[S->top];
return 1;
}
}


int main()
{
SqStack S;
initStack(&S);
int cot=5;
int tmp;
while(cot--)//循环五次
{
Push(&S,cot);
if(read_top(&S,&tmp))//读取栈顶元素,并返回
{
printf("top数值:%d\n",tmp);
}

}
//设置是5最大,再压一个看看结果,是否失败
Push(&S,6);

return 0;
}

 

 

 

posted @ 2022-07-15 23:05  天天掉头发  阅读(32)  评论(0编辑  收藏  举报
返回顶端