1.顺序表实现栈结构 :
#pragma once #include#include #include //#define N 10 //typedef int STDataType; //typedef struct Stack //{ // STDataType a[N]; // int top; //}ST; typedef int STDataType; typedef struct Stack { STDataType* a; int top; int capacity; }ST; void StackInit(ST* ps); void StackDestroy(ST* ps); void StackPush(ST* ps, STDataType x); void StackPop(ST* ps); STDataType StackTop(ST* ps); bool StackEmpty(ST* ps); int StackSize(ST* ps); #include "stck.h" void StackInit(ST* ps) { assert(ps); ps->a=NULL; ps->top = 0; ps->capacity = 0; } void StackDestroy(ST* ps) { assert(ps); free(ps->a); ps->a =NULL; ps->top = ps->capacity=0; } void StackPush(ST* ps, STDataType x) { assert(ps); if(ps->top == ps->capacity) { int newCapcity = ps->capacity==0?4:ps->capacity*2; STDataType* tmp = (STDataType*)realloc(ps->a,sizeof(STDataType)*newCapcity); if(tmp==NULL) { printf("realloc failn"); exit(-1); } ps->a = tmp; ps->capacity = newCapcity; } ps->a[ps->top] = x; ps->top++; } void StackPop(ST* ps) { assert(ps); assert(!StackEmpty(ps)); ps->top--; } STDataType StackTop(ST* ps) { return ps->a[ps->top-1]; } bool StackEmpty(ST* ps) { return ps->top==0; } int StackSize(ST* ps) { return ps->top; }



