SqStack.h头文件 #ifndef SQSTACK_H_H #define OK 0 #define ERROR -1 #define MAX_SIZE 100 typedef int type; typedef struct SNode { type *base; type *top; int stack_size; int stack_length; }SqStack; int init_stack(SqStack*); int destroy_stack(SqStack*); int clear_stack(SqStack*); int stack_empty(SqStack); int stack_length(SqStack); int get_top(SqStack, type*); int push(SqStack*, type); int pop(SqStack*, type*); int create_stack(SqStack*); int print_stack(SqStack*); #endif SqStack.cpp文件 #include<stdio.h> #include<stdlib.h> #include "SqStack.h" int init_stack(SqStack *stack) { if(!(stack->base = (type*)malloc(sizeof(type) * MAX_SIZE))) return ERROR; stack->top = stack->base; stack->stack_size = MAX_SIZE; stack->stack_length = 0; return OK; } int destroy_stack(SqStack *stack) { if(stack->base == NULL) return ERROR; free(stack->base); stack->base = NULL; stack->top = NULL; stack->stack_size = 0; stack->stack_length = 0; return OK; } int clear_stack(SqStack *stack) { if(stack->base == NULL || stack->stack_length == 0) return ERROR; stack->top = stack->base; stack->stack_length = 0; return OK; } int stack_empty(SqStack stack) { if(stack.base == NULL) return ERROR; if(0 == stack.stack_length) return true; return false; } int stack_length(SqStack stack) { if(stack.base == NULL) return ERROR; return stack.stack_length; } int get_top(SqStack stack, type *e) { if(stack.base == NULL || stack.stack_length == 0) { *e = -1; return ERROR; } *e = *(--stack.top); return OK; } int push(SqStack *stack, type e) { if(stack->base == NULL) return ERROR; if((stack->top + 1) - stack->base > stack->stack_size) return ERROR; *stack->top++ = e; stack->stack_length++; return OK; } int pop(SqStack *stack, type *e) { if(stack->base == NULL || stack->stack_length == 0) return ERROR; if(stack->top - 1 < stack->base) return ERROR; *e = *(--stack->top); stack->stack_length--; return OK; } int create_stack(SqStack *stack) { if(stack->base == NULL) return ERROR; type num; printf("input num: "); scanf("%d",&num); while(num != 0) { push(stack,num); scanf("%d",&num); } return OK; } int print_stack(SqStack *stack) { if(stack->base == NULL || stack->stack_length == 0) return ERROR; type *tmp = stack->top; while((--tmp) != stack->base - 1) { printf("%d ",*tmp); } printf("/n"); return OK; }