头文件 sqStack.h
#ifndef _SQSTACK_H_
#define _SQSTACK_H_
#include<stdio.h>
#include<stdlib.h>
typedef int datatype;
typedef struct{
datatype *data; //用指针指向栈的存储空间
int maxlen; //当前栈的最大元素个数
int top; //指示栈顶位置(数组下标)的变量
}sqstack;
sqstack *stack_create(int len); //创建一个空栈
int stack_empty(sqstack *s); //判断栈是否为空
void stack_clear(sqstack *s); //把栈清空
int stack_full(sqstack *s); //判断栈是否为满
int stack_push(sqstack *s,datatype value); //元素入栈
datatype stack_pop(sqstack *s); //元素出栈
datatype stack_top(sqstack *s); //取栈顶元素
sqstack *stack_create(int len) //创建一个空栈
{
sqstack *s;
if((s = (sqstack *)malloc(sizeof(sqstack))) == NULL)
{
printf("malloc failed!\n");
return NULL;
}
if((s->data = (datatype *)malloc(len * sizeof(datatype))) == NULL)
{
printf("malloc failed\n");
return NULL;
}
s->maxlen = len;
s->top = -1; //因为最开始是个空栈
return s;
}
int stack_empty(sqstack *s) //判断栈是否为空
{
//1代表为空栈 ,0为非空
return (s->top == -1 ? 1 : 0);
}
void stack_clear(sqstack *s) //把栈清空
{
s->top=-1; //栈顶指针为-1,,说明栈中没有元素了
}
int stack_full(sqstack *s) //判断栈是否为满
{
return (s->top == s->maxlen-1 ? 1 : 0); //减一因为元素下标从0开始
}
int stack_push(sqstack *s,datatype value) //元素入栈
{
//先判断栈是否满了
if(s->top == s->maxlen-1)
{
printf("stack is full\n");
return -1;
}
s->data[s->top+1] = value;
s->top++;
return 1;
}
datatype stack_pop(sqstack *s) //元素出栈
{
s->top--;
return s->data[s->top+1];
}
datatype stack_top(sqstack *s) //取栈顶元素
{
return (s->data[s->top]);
}
#endif
测试文件 testStack.c
#include "sqStack.h"
int main()
{
sqstack *s;
int i,n,data;
printf("请输入想要创建的空栈可容纳元素的个数n:\n");
scanf("%d",&n);
s=stack_create(n); //创建一个空栈
printf("下面开始输入元素进栈:\n");
for(i=0;i<n;i++)
{
scanf("%d",&data);
stack_push(s,data);
}
if(stack_full(s))
printf("此时栈的状态是满的\n");
printf("栈顶元素为:%d\n",stack_top(s));
printf("下面开始元素出栈:\n");
if(stack_empty(s)) //如果栈为空
{
printf("stack is empty!\n");
}
else
{
while(!stack_empty(s)) //只要栈非空
{
printf("%d ",stack_pop(s));
}
printf("\n");
}
return 0;
}