栈的实现实例(C语言)

/* stack.h */

#ifndef _stack_h
#define _stack_h

struct stack_record;
typedef struct stack_record *stack;
typedef int element_type;

int is_empty( stack s );
int is_full( stack s );
stack create_stack( int max_elements );
void dispose_stack( stack s );
void make_empty( stack s );
void push( element_type x, stack s );
element_type top( stack s );
void pop( stack s );
element_type top_and_pop( stack s );

#endif
/* stack.c */

#include "stack.h"
#include <stdio.h>
#include <stdlib.h>


#define    MIN_STACK_SIZE    5

struct stack_record
{
    int capacity;
    int top_of_stack;
    element_type *array;
};

stack
create_stack( int max_elements )
{
    stack s;
    
    if( max_elements < MIN_STACK_SIZE )
    {
        printf( "Stack size is too small\n" );
        exit(0);
    }

    s = malloc( sizeof( struct stack_record ));
    if( s == NULL )
    {
        printf( "Out of sapce\n" );
        exit(1);
    }

    s->array = malloc( sizeof( element_type ) * max_elements );
    if( s->array == NULL )
    {
        printf( "Out of space\n" );
        exit(1);
    }

    s->capacity = max_elements;
    make_empty( s );

    return s;
}

void 
dispose_stack( stack s )
{
    if( s != NULL )
    {
        free( s->array );
        free( s );
    }
}

int 
is_empty( stack s )
{
    return s->top_of_stack == -1;
}

int
is_full( stack s )
{
    return s->capacity == s->top_of_stack + 1;
}

void
make_empty( stack s )
{
    s->top_of_stack = -1;
}

void
push( element_type x, stack s )
{
    if( is_full( s ) )
    {
        printf( "Full stack!\n" );
        exit(0);
    }
    else
        s->array[++s->top_of_stack] = x;
}

element_type
top( stack s )
{
    if( !is_empty( s ) )
        return s->array[s->top_of_stack];
    else
    {
        printf( "Empty stack\n" );
        exit(0);
    }
    
    return 0;
}

void
pop( stack s )
{
    if( is_empty( s ) )
    {
        printf ("Empty stack\n");
        exit(0); 
    }
    else
        s->top_of_stack--;
}

element_type
top_and_pop( stack s )
{
    if( !is_empty( s ) )
        return s->array[s->top_of_stack--];
    else
    {
        printf( "Empty stack\n" );
        exit(0);
    }

    return 0;
}
/* stack_test.c */

#include "stack.h"
#include <stdio.h>

int
main(void)
{
    stack s;
    int x;
    int y;
    int z;

    s = create_stack(10);    

    push( 1, s );
    push( 2, s );
    push( 3, s );
    
    x = top_and_pop( s );
    y = top_and_pop( s );
    z = top_and_pop( s );
    printf("%d\n%d\n%d\n", x, y, z);

    dispose_stack( s );
    return 0;
}

 

测试结果:

image

posted @ 2014-03-19 08:38  ITtecman  阅读(2662)  评论(0编辑  收藏  举报