1.基本操作代码
#include <stdio.h>
#include <stdlib.h>
#define STACK_SIZE 10 /*初始存储空间*/
typedef int elemType; /*定义元素类型*/
typedef struct{
elemType *base;
elemType *top;
int stacksize; /*已分配存储空间*/
} SqStack;
void InitStack(SqStack *S); /*构造空栈*/
int push(SqStack *S, elemType e); /*入栈*/
int Pop(SqStack *S, elemType *e); /*出栈*/
int CreateStack(SqStack *S); /*创建栈*/
void PrintStack(SqStack *S); /*输出栈中元素*/
void InitStack(SqStack *S) {
S->base = (elemType *) malloc (STACK_SIZE * sizeof (elemType));
S->top = S->base;
S->stacksize = STACK_SIZE;
}
int Push(SqStack *S, elemType e) {
if (S->top - S->base == S->stacksize) {
S->base = (elemType*) malloc (STACK_SIZE * sizeof (elemType));
if(!S->base) {
return 0;
S->top = S->base + S->stacksize;
S->stacksize = S->stacksize + STACK_SIZE;
}
}
*S->top = e;
S->top++;
}
int Pop(SqStack *S, elemType *e) {
if(S->top == S->base) {
return 0;
}
else {
--S->top;
*e = *S->top;
}
}
int CreateStack(SqStack *S) {
int e;
InitStack(S);
printf("Push:\n");
while(scanf("%d", &e)) {
Push(S,e);
}
}
void PrintStack(SqStack *S) {
elemType e;
while(Pop(S, &e)){
printf("%d ", e);
}
}
void main(void) {
SqStack ss;
CreateStack(&ss);
printf("Pop:\n");
PrintStack(&ss);
}
2.运行结果
![](https://i-blog.csdnimg.cn/direct/a25ecbb4f2094d769ec29eb124a57900.png)