堆疊的實現(1)--靜態陣列

dark9527發表於2018-05-17

堆疊也可以說是一種特殊的線性表,只能在棧頂進行插入和刪除。

本文中的堆疊實現採用靜態陣列實現,缺點是編譯時確定了長度。優點是簡單,不易出錯。

這個是標頭檔案的宣告,每個函式的功能都有註釋。

#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;
}

相關文章