堆栈的实现(1)--静态数组

堆栈也可以说是一种特殊的线性表,只能在栈顶进行插入和删除。

本文中的堆栈实现采用静态数组实现,缺点是编译时确定了长度。优点是简单,不易出错。

这个是头文件的声明,每个函数的功能都有注释。

#ifndef A_STACK_H
#define A_STACK_H 
/*
** Interface for a stack module
*/
#define	STACK_SIZE	100	/* Max # of values on the stack */
/*
** push
**	Pushes a new value on the stack.  The argument is the value
**	to be pushed.
*/
void	push( int value );

/*
** pop
**	Pops a value off of the stack, discarding it.
*/
void	pop( void );

/*
** top
**	Returns the topmost value on the stack without changing the
**	stack.
*/
int top( void );

/*
** is_empty
**	Returns TRUE if the stack is empty, else FALSE.
*/
int	is_empty( void );

/*
** is_full
**	Returns TRUE if the stack is full, else FALSE.
*/
int	is_full( void );
/*
**print
** print the data in the stack
*/
void print(void);
/*
**count
** count the data in the stack
*/
int count(void);
#endif

头文件中声明函数的实现

/*
** A stack implemented with a static array.  The array size can
** be adjusted only by changing the #define and recompiling
** the module.
*/
#include "a_stack.h"
#include <assert.h>
#include <stdio.h>


/*
**	The array that holds the values on the stack, and a pointer
**	to the topmost value on the stack.
*/
static	int	stack[ STACK_SIZE ];
static	int	top_element = -1;

/*
**	push
*/
void
push( int value )
{
	assert( !is_full() );
	top_element += 1;//top_element先加一,再赋值
	stack[ top_element ] = value;
}

/*
**	pop
*/
void
pop( void )
{
	assert( !is_empty() );
	top_element -= 1;
}

/*
**	top
*/
int top( void )
{
	assert( !is_empty() );
	return stack[ top_element ];
}

/*
**	is_empty
*/
int
is_empty( void )
{
	return top_element == -1;
}

/*
**	is_full
*/
int
is_full( void )
{
	return top_element == STACK_SIZE - 1;
}
/*
**count
** 
*/
int count(void)
{
	return top_element+1;
}
/*
**print
** 
*/
void print()
{
	assert( !is_empty() );
	int i;
	for(i=0;i<count();i++)
	{
		printf(" %d-->%d ",i,stack[i]);
		if((i+1)%5==0)
		printf("\n");
	}
}

实现函数的测试

#include "a_stack.h"
#include<stdio.h>
#include<stdlib.h>
#include<time.h>


int main(void)
{
	int i;
	srand((unsigned int)time(NULL));
	for(i=0;i<STACK_SIZE;i++)
	push(rand()%100);
	print();
	for(i=0;i<10;i++)
	pop();
	print();
	printf("top-->%d\n",top());
	return 0;
}

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值