堆栈的实现(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;
}

阅读更多

没有更多推荐了,返回首页