#include<stdio.h>
#define MaxStackSize 100
typedef int DataType;
typedef struct //定义结构体
{
DataType stack[MaxStackSize];
int top;
}SeqStack;
void InitStack(SeqStack *s) //初始化
{
s->top = 0;
}
int StackNotEmpty(SeqStack s) //判断顺序堆栈非空否
{
if(s.top <= 0)
{
return 0;
}
else
{
return 1;
}
}
int Push(SeqStack *s,int x) //入栈
{
if(s->top >= MaxStackSize)
{
printf("堆栈已满,无法插入!\n");
return 0;
}
s->stack[s->top] = x;
s->top++;
return 1;
}
int Pop(SeqStack *s,int *x) //出栈
{
if(s->top <= 0)
{
printf("堆栈已空!\n");
return 0;
}
s->top--;
*x = s->stack[s->top];
return 1;
}
int StackTop(SeqStack s,int *x) //取栈顶元素
{
if(s.top <= 0)
{
printf("堆栈已空无数据元素出栈!\n");
return 0;
}
*x = s.stack[s.top-1];
return 1;
}
int main()
{
SeqStack s;
int x,i;
InitStack(&s);
for(i=0;i<10;i++)
{
Push(&s,i+1);
}
StackTop(s,&x);
printf("当前栈顶数据元素为:%d\n",x);
printf("依次出栈的数据元素序列如下:\n");
while(StackNotEmpty(s))
{
Pop(&s,&x);
printf("%d ",x);
}
return 0;
}
顺序堆栈的操作实现
最新推荐文章于 2022-01-13 23:14:32 发布