#include <stdio.h>
#include <stdlib.h>
// 初始长度
#define STACK_INIT_SIZE 10
// 扩容量
#define STACK_INCREMENT 100
typedef int ElemType;
// 栈的顺序存储结构
typedef struct {
// 栈顶指针
ElemType *top;
// 栈底指针
ElemType *base;
// 栈长
int stackSize;
} Stack;
// 创建栈
int initStack(Stack &S);
// 判断栈是否为空
int isEmpty(Stack &S);
// 栈扩容
int grow(Stack &S);
// 入栈
int push(Stack &S, ElemType e);
// 出栈
int pop(Stack &S);
// 求栈长
int length(Stack &S);
// 清空栈
int clear(Stack &S);
int initStack(Stack &S) {
S.base = (ElemType *) malloc(STACK_INIT_SIZE * sizeof(ElemType));
if (!S.base)return -1;
S.top = S.base;
S.stackSize = STACK_INIT_SIZE;
return 0;
}
int isEmpty(Stack &S) {
if (S.base == S.top) {
printf("stack is empty");
exit(-1);
}
return 0;
}
int grow(Stack &S) {
if (S.top - S.base >= S.stackSize) {
// 重新分配存储空间
S.base = (ElemType *) realloc(S.base, (S.stackSize + STACK_INCREMENT) * sizeof(ElemType));
if (!S.base)return -1;
S.top = S.base + S.stackSize;
S.stackSize += STACK_INCREMENT;
}
return 0;
}
int push(Stack &S, ElemType e) {
grow(S);
// e赋值给栈顶指针所指的空间,然后指针上移一位
*S.top++ = e;
return 0;
}
ElemType pop(Stack &S) {
isEmpty(S);
// 栈顶指针是指向最后一个入栈的元素的后一位
return *--S.top;
}
int length(Stack &S) {
int len = 0;
ElemType *temp = S.top;
while (temp != S.base) {
len++;
temp--;
}
return len;
}
int clear(Stack &S) {
while (S.top != S.base) {
*--S.top = NULL;
}
return 0;
}
int main() {
Stack S;
// 创建栈
initStack(S);
printf("When there is no element on the stack, the stack length is:%d\n", length(S));
// 10个元素入栈
for (int i = 0; i < 10; ++i) {
push(S, i + 1);
}
printf("After 10 elements are put on the stack, the stack length is:%d\n", length(S));
// 10个元素出栈
for (int i = 0; i < 10; ++i) {
printf("%d ", pop(S));
if(i == 9)printf("\n");
}
printf("After 10 elements are popped out of the stack, the stack length is:%d\n", length(S));
// 清空栈
clear(S);
printf("After clearing the stack, the stack length is:%d\n", length(S));
push(S, 419);
printf("%d\n", pop(S));
return 0;
}
运行结果