static_shuzu_stack.h
/*
*构造静态数组栈
*/
#ifndef STATIC_SHUZU_STACK
#define STATIC_SHUZU_STACK
#define STACK_TYPE int//定义栈数据类型
#define STACK_SIZE 9//定义栈静态数据长度
//push入栈
void push(STACK_TYPE value);
//pop出栈
void pop(void);
//top 获得栈顶元素
STACK_TYPE top(void);
//is_full //判断栈是否满
int is_full(void);
//is_empty //判断栈是否空
int is_empty(void);
#endif /*STATIC_SHUZU_STACK*/
static_shuzu_stack.c
/*
*构造静态数组栈
*/
#include
#include "static_shuzu_stack.h"
#include
static STACK_TYPE stack[STACK_SIZE]; //定义栈
static int top_element=-1; //定义栈顶位置
//push入栈
void push(STACK_TYPE value)
{
assert(!is_full());
top_element++;
stack[top_element]=value;
}
//pop出栈
void pop(void)
{
assert(!is_empty());
top_element--;
}
//top 获得栈顶元素
STACK_TYPE top(void)
{
return stack[top_element];
}
//is_full //判断栈是否满
int is_full(void)
{
return top_element==STACK_SIZE;
}
//is_empty //判断栈是否空
int is_empty(void)
{
return top_element==-1;
}
/*
* 可以设定从栈底开始存放数据,这样在push()时需要在添加之后再将top_element++,
* 但是在出栈的时候需要首先将top_elemnt--,然后再将top_element--;
* 影响了效率
*/
static_shuzu_stacktest.c
/*
* 编写测试用例
*/
#include
#include "static_shuzu_stack.h"
void main()
{
int i=0;
for(i=0;i<=10;i++)
{
if(is_full())
{
printf("stack is full now\n");
break;
}
push(i);
printf("top of stack is %d\n",top());
}
for(i=0;i<=10;i++)
{
if(is_empty())
{
printf("stack is empty now\n");
break;
}
printf("top of stack is %d\n",top());
pop();
}
}
编译:gcc -o staticTest static_shuzu_stack.c static_shuzu_stacktest.c
输出结果:
top of stack is 0
top of stack is 1
top of stack is 2
top of stack is 3
top of stack is 4
top of stack is 5
top of stack is 6
top of stack is 7
top of stack is 8
top of stack is 9
stack is full now
top of stack is 9
top of stack is 8
top of stack is 7
top of stack is 6
top of stack is 5
top of stack is 4
top of stack is 3
top of stack is 2
top of stack is 1
top of stack is 0
stack is empty now