#define ERROR 0#define OK 1#define OVERFLOW -1typedef int Status;typedef int SElemType;typedef struct SNode{ SElemType data; struct SNode *next;}SNode;typedef struct{ SNode *top;}LinkStack;void InitStack(LinkStack *S){ assert(S); S->top = NULL;}void DestroyStack(LinkStack *S){ assert(S); SNode *tmp = S->top; while (tmp) { S->top = tmp->next; free(tmp); tmp = S->top; }}Status StackEmpty(LinkStack *S){ assert(S); return NULL == S->top;}Status Push(LinkStack *S, SElemType e){ assert(S); SNode *tmp; tmp = (SNode *)malloc(sizeof(SNode)); if (!tmp) exit(OVERFLOW); tmp->data = e; tmp->next = S->top; S->top = tmp; return OK;}Status Pop(LinkStack *S, SElemType *e){ assert(S); SNode *tmp; if (StackEmpty(S)) return ERROR; tmp = S->top; S->top = tmp->next; if (e) *e = tmp->data; free(tmp); return OK;}Status GetTop(LinkStack *S, SElemType *e){ assert(S); if (StackEmpty(S)) return ERROR; *e = S->top->data; return OK;}void StackTraverse(LinkStack *S, void(*visit)(SElemType *)){ assert(S&&visit); SNode *tmp; tmp = S->top; while (tmp) { visit(&tmp->data); tmp = tmp->next; }}
测试程序:
#include#include #include void visit(SElemType *e){ putchar(*e);}int main(){ LinkStack S; int c; InitStack(&S); while ('\n' != (c = getchar())) Push(&S, c); StackTraverse(&S, visit); putchar('\n'); while (!StackEmpty(&S)) { Pop(&S, &c); visit(&c); } DestroyStack(&S); putchar('\n'); system("pause"); return 0;}
运行结果:
栈的顺序存储实现请戳