Introduction:
Using a linked list to implement a stack has the disadvantages of "expensive to call malloc and free", especially compared with the pointer operation routine. Using arrays to implement stacks can avoid pointers. However, its disadvantage is that there may be a waste of space.
Analysis description:
The node element of the array stack.
#ifndef ERROR#define ERROR (0)#endif#ifndef OK#define OK(!ERROR)#endif#define STACK_INIT_SIZE 100#define STACKINCREMENT 10typedefint SElemType;typedef struct SqStack{SElemType*base;SElemType*top;intstacksize;}SqStack, *pStack;pStack S;
Stack initialization.
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;}
Stack operations.
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;}
Out-of-stack operations.
SElemType Pop(pStack S){if(S->top == S->base)return 0;return *(--S->top);}
Take the top element of the stack.
SElemType GetTop(pStack S){if(S->top == S->base)return ERROR;return *(S->top - 1);}
Evaluate the stack length.
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;}