和用静态数组的唯一区别在于,申请的是堆内存而非栈内存,且数组的大小可以任意调整~~ /************************************************************************/ /* author : thomas E-mail: chenhua308@gmail.com */ /************************************************************************/ #include <stdio.h> #include <malloc.h> typedef int T; typedef struct tag { int Top, MaxSize; T *elememtsp; } STACK; void creat(STACK *stack, int size) { stack -> Top = -1; stack -> MaxSize = size - 1; stack -> elememtsp = (T *)malloc(size * sizeof(T)); } int is_empty( STACK stack ) { if ( stack.Top == -1 ) { return 1; } else { return 0; } } int is_full( STACK stack ) { if ( stack.Top == stack.MaxSize ) { return 1; } else { return 0; } } int top( STACK stack ) { if ( stack.Top == -1 ) { printf("the stack is empty! /n"); return 10000; } else { return *(stack.elememtsp + stack.Top); } } void pop( STACK *stack ) { if ( 1 == is_empty(*stack) ) { printf("the stack is empty! pop is not available! /n"); } else { stack -> Top--; } } void push( STACK *stack, T value ) { if ( 1 == is_full(*stack)) { printf("the stack is full! push is not available! /n"); } else { stack -> Top++; *(stack -> elememtsp + stack -> Top) = value; } } void destory( STACK *stack ) { stack -> Top = -1; stack -> MaxSize = 0; free(stack -> elememtsp); } void printstack( STACK stack ) { int i = 0, count; count = stack.Top; if ( stack.Top == -1 ) { printf("the stack is empty! /n"); } else { printf("the number of the stack is: %d /n", stack.Top + 1); for ( i; i <= stack.Top; i++ ) { printf("the %d number is %d /n", i, *(stack.elememtsp + i)); } } } //test the functions void main(int argc, char *argv[]) { STACK stack; creat(&stack, 5); //is_empty(stack); pop(&stack); push(&stack, 3); printstack(stack); push(&stack, 4); printstack(stack); }