• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

栈的实现实例(C语言)

原作者: [db:作者] 来自: [db:来源] 收藏 邀请
/* 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;
}

 

测试结果:


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap