c语言静态数组创建栈

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 <stdio.h>
#include "static_shuzu_stack.h"
#include <assert.h>

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 <stdio.h>
#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

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值