#include <stdio.h>
#include <stdlib.h>
#define MAXSIZE 10
#define DATATYPE int
typedef struct
{
DATATYPE data[MAXSIZE];
int top;
}SeqStack;
SeqStack * Init_SeqStack(void);
int Empty_SeqStack(SeqStack *s);
int Full_SeqStack(SeqStack *s);
int Push_SeqStack(SeqStack *s,DATATYPE x);
int Pop_SeqStack(SeqStack *s,DATATYPE x);
DATATYPE Top_SeqStack(SeqStack *s);
void Destroy(SeqStack *s);
SeqStack * Init_SeqStack(void)
{
SeqStack *s=NULL;
s=(SeqStack *)malloc(sizeof(SeqStack));
if(s==NULL)
{
exit(0);
}
else
{
s->top=-1;
//s->data[MAXSIZE]={0};
}
return s;
}
int Empty_SeqStack(SeqStack *s)
{
return(s->top==-1); // if s->top==-1,return 1 ,else return 0;
}
int Full_SeqStack(SeqStack *s)
{
return(s->top==MAXSIZE); // if s->top==MAXSIZE,return 1; else return 0;
}
int Push_SeqStack(SeqStack *s,DATATYPE x)
{
int flag=0;
flag=Full_SeqStack(s);
if(!flag)
{
s->top++;
s->data[s->top]=x;
printf("The in stack element is %d \n",x);
return 0;
}
else
{
printf("The stack is full,the program is ended.\n");
exit(0);
}
}
int Pop_SeqStack(SeqStack *s,DATATYPE x)
{
int flag=0;
flag=Empty_SeqStack(s);
if(!flag)
{
x=s->data[s->top];
printf("The out stack element is %d \n",x);
s->top--;
return 0;
}
else
{
printf("The stack is empty, the program is ended .\n");
exit(0);
}
}
DATATYPE Top_SeqStack(SeqStack *s)
{
DATATYPE x;
int flag;
flag=Empty_SeqStack(s);
if(!flag)
{
x=s->data[s->top];
printf("The top element of the stack is %d \n",x);
return x;
}
else
{
printf("The stack is empty,ends the program.\n");
exit(0);
}
}
void Destroy(SeqStack *s)
{
free(s);
s=NULL;
return 0;
}
int main()
{
SeqStack *s=NULL;
DATATYPE a=1,b=2,c=3;
DATATYPE x=0;
s=Init_SeqStack( );
Push_SeqStack(s,a);
Push_SeqStack(s,b);
Push_SeqStack(s,c);
Pop_SeqStack(s,x);
Top_SeqStack(s);
Pop_SeqStack(s,x);
Pop_SeqStack(s,x);
Destroy(s);
return 0;
}
栈的基本用法(顺序存储结构)
最新推荐文章于 2025-08-19 21:26:23 发布
本文介绍了一个简单的栈数据结构实现,并展示了如何使用C语言进行基本的操作,包括初始化、判断空满状态、元素入栈与出栈及获取栈顶元素等。
&spm=1001.2101.3001.5002&articleId=45508765&d=1&t=3&u=8e93814a6f7b4f6fa5ee964521a9474a)
4642

被折叠的 条评论
为什么被折叠?



