/*
1.struct--top , base
2.创建空表
3.插入元素
4.遍历表
5.出栈
6.销毁表
7.判断空栈
8.栈的长度
注意:插入栈与栈出都是一个元素一个元素的
*/
typedef int Element;//变量头
typedef int status; //函数头
typedef struct {
Element* top;
Element* base;
int stack_size;
}Stack;
//2.创建空表
status Initstack(Stack* S) {
S->base = (Element*)malloc(sizeof(int));
S->top = S->base;
S->stack_size = MAX;
return 0;
}
//3.插入元素
status Insert(Stack* S, int e) {
if ((S->top - S->base) >= S->stack_size) {
printf("上溢\n");
exit(1);
}
*(S->top) = e;
S->top++;
return 1;
}
//遍历表
void show(Stack* S) {
Element* p;
if (S->base == S->top) {
printf("空表\n");
}
p = S->top;
while (p > S->base) {
p--;
printf("%d ", *p);
}
}
//出栈
status popStack(Stack* S, int* e) {
if (S->base == S->top) {
printf("又是你\n");
return 0;
}
--S->top;
*e = *S->top;
return 1;
}
//6.销毁表
status destory(Stack* S) {
free(S);
S->base = S->top = NULL;
S->stack_size = 0;
return 1;
}
//长度
status length(Stack* S) {
if (S->top == S->base) {
printf("空表\n");
return 0;
}
return (status)(S->top - S->base);
}
//栈顶数据(感觉有问题)
int topStack(Stack* S, int * n) {
if (S->top == S->base) {
printf("空表\n");
return 0;
}
*n = *(--S->top);
return 1;
}
int main(void){
Stack* m;
m = (Stack*)malloc(sizeof(Stack));
Initstack(m);
int nums[5] = { 12,45,2,36,8 };
for (int i = 0; i < 5; i++) {
Insert(m, nums[i]);
}
show(m);
printf("\n-----------------------\n");
int n;
popStack(m, &n);
show(m);
/*printf("\n----------------\n");
destory(m);
show(m);*/
printf("\n----------------\n");
printf("%d", length(m));
printf("\n----------------\n");
int q;
topStack(m, &q);
printf("%d", q);
return 0;
}
栈 :先进后出