用到的头文件
#define STACK_INIT_SIZE 10
#define STACK_INCREMENT 2
typedef int SElemType;
typedef int Status;
#define TRUE 1
#define FALSE 0
struct SqStack
{
SElemType *base;
SElemType *top;
int stacksize;
};
实现代码:
```c
#include<stdio.h>
#include "stack.h"
#include<stdlib.h>
//初始化栈
void InitStack(SqStack& S){
if (!(S.base = (SElemType*)malloc(STACK_INIT_SIZE*sizeof(SElemType))))
exit(0); //分配栈底指针失败
S.top = S.base;
S.stacksize = STACK_INIT_SIZE;
}
//销毁栈
void DestroyStack(SqStack& S){
free(S.base);
S.base = NULL;
S.top = NULL;
S.stacksize = 0;
}
//置为空栈
void ClearStack(SqStack& S){
S.top = S.base;
}
//判断是否栈空
Status StackEmpty(SqStack& S){
if (S.top == S.base) return TRUE;
return FALSE;
}
//返回栈长
Status StackLength(SqStack& S){
return S.top - S.base;
}
//取栈顶元素
Status GetTop(SqStack& S, SElemType &e){
if (S.base == S.top) return FALSE;
e = *--S.top;
return e;
}
//进栈
void Push(SqStack &S, SElemType e){
if (StackLength(S) < S.stacksize)
*(S.top++)= e;
else{
S.base = (SElemType*)realloc(S.base, STACK_INCREMENT*sizeof(SElemType));
if (!S.base) exit(0);
S.top = S.base + S.stacksize;
S.stacksize += STACK_INCREMENT;
}
}
//出栈
Status Pop(SqStack &S, SElemType& e){
if (S.stacksize == 0) return FALSE;
e = *--S.top;
return TRUE;
}
//遍历栈
void TraverStack(SqStack& S){
SElemType* p = S.top; //为了便利不去动原来的top和base指针
if (S.stacksize == 0) return;
while (p != S.base)
printf("%d ",*(--p));
}
int main(){
SqStack stack;
SElemType E = 0;
InitStack(stack);
for (int i = 0; i < 10; i++)
Push(stack, i);
TraverStack(stack);
printf("\n");
GetTop(stack, E);
printf("栈顶:%d\n ",E);
printf("栈的长度:%d\n", StackLength(stack));
printf("栈是否为空:%d\n", StackEmpty(stack));
DestroyStack(stack);//销毁栈
printf("栈的长度:%d\n", StackLength(stack));
ClearStack(stack);
printf("栈的长度:%d\n", StackLength(stack));
return 0;
}