引言:
使用链表实现栈存在“对malloc和free的调用开销昂贵”的缺点,特别是与指针操作的例程相比尤其如此。利用数组实现栈能够避免了指针。但它的缺点是可能存在空间的浪费。
分析描写叙述:
数组栈的结点元素。
#ifndef ERROR#define ERROR (0)#endif#ifndef OK#define OK (!ERROR)#endif#define STACK_INIT_SIZE 100#define STACKINCREMENT 10typedef int SElemType;typedef struct SqStack{ SElemType *base; SElemType *top; int stacksize;}SqStack, *pStack;pStack S;栈的初始化。
pStack InitStack(pStack S){ S = (pStack)malloc(STACK_INIT_SIZE * sizeof(SElemType)); if(S == NULL){ return ERROR; } S->base = (SElemType *)S; S->top = S->base; S->stacksize = STACK_INIT_SIZE; return S;}入栈操作。
pStack Push(pStack S, SElemType e){ if((S->top - S->base) >= S->stacksize){ S->base = (SElemType *)realloc(S, (S->stacksize + STACKINCREMENT)*sizeof(SElemType)); if(S->base == NULL) return ERROR; S->top = S->base + S->stacksize; S->stacksize += STACKINCREMENT; } *S->top++ = e; return S;}出栈操作。
SElemType Pop(pStack S){ if(S->top == S->base) return 0; return *(--S->top);}取栈顶元素。
SElemType GetTop(pStack S){ if(S->top == S->base) return ERROR; return *(S->top - 1);}求栈的长度。
int GetLength(pStack S){ int length = 0; if(S->top == S->base) return 0; pStack Tmp = S; while(Tmp->top-- != Tmp->base) length++; return length;}