【C基础】堆栈的实现

来源:互联网 发布:大宗商品期货软件 编辑:程序博客网 时间:2024/06/03 20:55

堆栈模块的非传统接口:

/* 一个堆栈模块的接口 */#define STACK_TYPE int  /* 堆栈所存储的值得类型 */void push( STACK_TYPE value ); /* 把值压入堆栈中 */void pop( void )  /* 从堆栈弹出一个值,并将其丢弃 */STACK_TYPE top( void ); /* 返回堆栈顶元素的值,但不对堆栈进行修改 */ int is_empty( void ) /* 判断堆栈是否为空 */int is_full( void ) /* 判断堆栈是否已满 */

用静态数组实现:
#include "stack.h"#include <assert.h>#define STACK_TYPE   100  /* 堆栈中值数量的最大限制 *//* 存储堆栈中值得数组和一个指向堆栈顶部元素的指针 */static STACK_TYPE  satck[ STACK_SIZE ];static int top_element = -1;void push( STACK_TYPE value ){    assert( !is_full() );    top_element += 1;    stack[ top_element ] = value;}void pop( void ){    assert( !is_empty() );    return stack[ top_element ];}int is_empty( void ){    return top_element == -1;}int is_full( void ){    return top_element == STACK_SIZE - 1;}


动态数组实现堆栈:

#include "stack.h"#include <stdio.h>#include <stdlib.h>#include <malloc.h>#include <assert.h>static STACK_TYPE *stack;static size_t stack_size;static int top_element = -1;void create_stack( size_t size ){    assert( stack_size == 0 );    stack_size = size;    stack = malloc( stack_size * sizeof( STACK_TYPE ) );    assert( stack != NULL );}void destroy_stack( void ){    assert( stack_size > 0 );    stack_size = 0;    free( stack );    stack = NULL;}void push( STACK_TYPE value ){    assert( !is_full() );    top_element += 1;    stack[ top_element ] = value;}void pop( void ){    assert( !is_empty() );    top_element -= 1;}STACK_TYPE top( void ){    assert( !is_empty() );    return stack[ top_element ];}int is_empty( void ){    assert( stack_size > 0 );    return top_element == -1;}int is_full( void ){    assert( stack_size > 0 );    return top_element == stack_size - 1;}


用链式实现堆栈:

#include "stack.h"#include <stdio.h>#include <stdlib.h>#include <malloc.h>#include <assert.h>#define FALSE 0/* 定义一个结构以存储堆栈元素,其中link字段将指向堆栈的下一个元素 */typedef struct STACK_NODE{    STACK_TYPE value;    struct STACK_NODE *next;}StackNode;/* 指向堆栈中第一个节点的指针 */static StackNode *stack;/* create_stack */void create_stack( size_t size ){}/* destroy_stack */void destroy_stack( void ){    while( !is_empty() )        pop();}/* push */void push( STACK_TYPE value ){    StackNode *new_node;    assert( !is_empty() );    first_node = stack;    stack = first_node -> next;    free( first_node );}/* top */STACK_TYPE top( void ){    assert( !is_empty() );    return stack -> value;}/* is_empty */int is_empty( void ){    return stack == NULL;}/* is_full */int is_full( void ){    return FALSE;}



 


0 0
原创粉丝点击