1、seqstack.h
#ifndef __SEQSTACK_H__
#define __SEQSTACK_H__
#define MAX 10
typedef int datatype;
typedef struct
{
datatype data[MAX];
int top; //栈顶元素下标
}seqStack;
//创建
seqStack *create();
//判空
int empty(seqStack *S);
//判满
int full(seqStack *S);
//入栈(进栈/压栈)
int push(seqStack *S,datatype e);
//出栈(弹栈)
int pop(seqStack *S);
//遍历栈
void show(seqStack *S);
//销毁栈
void destroy(seqStack *S);
#endif
2、seqstack.c
#include
#include
#include"seqstack.h"
//创建
seqStack *create()
{
seqStack *S = (seqStack *)malloc(sizeof(seqStack));
if(S == NULL)
{
printf("创建失败n");
return NULL;
}
//初始化
S->top = -1;
printf("创建成功n");
return S;
}
//判空
int empty(seqStack *S)
{
return S->top == -1? 1:0; //1表示空,0表示非空
}
//判满
int full(seqStack *S)
{
return S->top == MAX-1? 1:0; //1表示满,0表示不满
}
//入栈(进栈/压栈)
int push(seqStack *S,datatype e)
{
//判断逻辑
if(S == NULL || full(S))
{
printf("入栈失败n");
return -1;
}
//入栈操作
S->top++;
S->data[S->top] = e;
printf("入栈成功n");
return 0;
}
//出栈(弹栈)
int pop(seqStack *S)
{
if(S ==NULL || empty(S))
{
printf("出栈失败n");
return -1;
}
//出栈逻辑
printf("%d出栈成功n",S->data[S->top]);
S->top--;
return 0;
}
//遍历栈
void show(seqStack *S)
{
if(S == NULL || empty(S))
{
printf("遍历失败n");
return;
}
printf("栈顶到栈底元素分别是:");
for(int i=S->top;i>=0;i--)
{
printf("%dt",S->data[i]);
}
putchar(10);
}
//销毁栈
void destroy(seqStack *S)
{
while(S->top != -1)
{
pop(S);
free(S);
S=NULL;
}
printf("销毁成功n");
}
3、main.c
#include
#include
#include"seqstack.h"
int main(int argc, const char *argv[])
{
//创建
seqStack *S = create();
if(S == NULL)
{
return -1;
}
//入栈
push(S,3);
push(S,4);
push(S,7);
push(S,8);
push(S,1);
show(S);
//出栈
pop(S);
pop(S);
show(S);
//销毁栈
destroy(S);
show(S);
return 0;
}
执行结果: