废话不多说,直接上代码:
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<errno.h>
#define STACK_INIT_SIZE 100
#define STACKINCRESMENT 10
typedef struct Stack{
char *base, *top;
int stacksize;
}SqStack;
//栈操作
int InitStack(SqStack s);
int DestroyStack(SqStack s);
int ClearStack(SqStack s);
int StackEmpty(SqStack s);
int StackLength(SqStack s);
int GetTop(SqStack s, char e);
int PushStack(SqStack s, char e);
int PopStack(SqStack s, char e);
int StackTraverse(SqStack s, void(*visit)(char));
int InitStack(SqStack s) {
s.base = (char*)malloc(STACK_INIT_SIZE * sizeof(char));
if (!s.base) exit(EOVERFLOW);
s.top = s.base;
s.stacksize = STACK_INIT_SIZE;
return 1;
}
int DestroyStack(SqStack s) {
free(s.base);
s.base = NULL;
s.top = NULL;
s.stacksize = 0;
return 1;
}
int ClearStack(SqStack s) {
s.top = s.base;
return 1;
}
int StackEmpty(SqStack s) {
if (s.top == s.base) return 1;
else return 0;
}
int StackLength(SqStack s) {
return s.top - s.base;
}
int GetTop(SqStack s, char e) {
if (s.base == s.top) return 0;
else {
e = *(s.top - 1);
return 1;
}
}
int PushStack(SqStack s, char e) {
if (s.top-s.base>=s.stacksize - 1) {
s.base = (char*)realloc(s.base, (s.stacksize + STACKINCRESMENT) * sizeof(char));
if (!s.base) exit(EOVERFLOW);
s.stacksize = s.stacksize + STACKINCRESMENT;
}
*s.top = e;
s.top++;
return 1;
}
int PopStack(SqStack s, char e) {
if (s.base == s.top) return 0;
else {
e = *--s.top;
return 1;
}
}
int StackTraverse(SqStack s, void(*visit)(char)) {
char *p;
p = s.top;
while (s.top > s.base) {
visit(*--s.top);
printf(" ");
}
s.top = p;
return 1;
}
void visit(char e) {
printf("%c", e);
}