顺序栈的实现(ANSI C)

1、顺序栈ADT定义

#ifndef _seq_stack_h
#define _seq_stack_h

#define STACK_INIT_SIZE 100
#define STACK_INCR_SIZE 10

typedef struct seq_stack
{
	int * base;
	int * top;
	int size;
}seq_stack;

void init_stack_sq( seq_stack * ss );
void clear_stack_sq( seq_stack * ss );
void free_stack_sq( seq_stack * ss );

int stack_size_sq( seq_stack * ss );
int is_stack_empty_sq( seq_stack * ss );

int get_top_sq( seq_stack * ss, int * e );
int push_sq( seq_stack * ss, int e );
int pop_sq( seq_stack * ss, int * e );

void traverse_stack_sq( seq_stack * ss );

#endif

2、实现

#include "seq_stack.h"

#include <stdlib.h>
#include <stdio.h>
#include <assert.h>

void init_stack_sq( seq_stack * ss )
{
	ss->size = STACK_INIT_SIZE;
	ss->top = ss->base = ( int * )malloc( sizeof( int ) * ss->size );
	assert( ss->base != NULL );
}

void clear_stack_sq( seq_stack * ss )
{
	assert( ss != NULL );
	ss->top = ss->base;
}

void free_stack_sq( seq_stack * ss )
{
	assert( ss != NULL && ss->base != NULL );
	ss->size = 0;
	free( ss->base );
	ss->base = ss->top = NULL;
}

int stack_size_sq( seq_stack * ss )
{
	assert( ss != NULL );
	return ss->size;
}

int is_stack_empty_sq( seq_stack * ss )
{
	assert( ss != NULL && ss->base != NULL );
	return ss->base == ss->top;
}

void traverse_stack_sq(  seq_stack * ss )
{
	int * p = NULL;
	assert( ss != NULL && ss->base != NULL );
	for( p = ss->base; p < ss->top; ++p )
		printf( "%d ", *p );
	putchar( '\n' );
}

int get_top_sq(  seq_stack * ss, int * e )
{
	assert( ss != NULL && ss->base != NULL );
	if( ss->base == ss->top )
		return -1;

	*e = *( ss->top - 1 );
	return 1;
}

int is_stack_full_sq( seq_stack * ss )
{
	return ss->base + ss->size == ss->top;
}

void expand_stack( seq_stack * ss )
{
	int * new_base = NULL, i;
	new_base = ( int * )malloc( sizeof( int ) * ( ss->size + STACK_INCR_SIZE ) );
	assert( new_base != NULL );
	for( i = 0; i < ss->size; ++i )
		new_base[i] = ss->base[i];
	free( ss->base );
	ss->base = new_base;
	ss->top = ss->base + ss->size;
	ss->size += STACK_INCR_SIZE;
}

int push_sq( seq_stack * ss, int e )
{
	assert( ss != NULL && ss->base != NULL );

	if( is_stack_full_sq( ss ) )
		expand_stack( ss );

	*ss->top++ = e;
	return 1;
}

int pop_sq( seq_stack * ss, int * e )
{
	assert( ss != NULL && ss->base != NULL );
	if( ss->base == ss->top )
		return -1;
	*e = *--ss->top;
	return 1;
}

你可能感兴趣的:(c,struct,null)