#include <stdio.h> #include <malloc.h> #define OK 1 #define ERROR 0 #define INFEASIBLE -1 #define OVERFLOW -2 #define TRUE 1 #define FALSE 0 #define STACK_INIT_SIZE 100 #define STACKINCREMENT 10 typedef int Status; typedef struct{ int *base; int *top; int stacksize; }SqStack; Status InitStack(SqStack &S); Status ClearStack(SqStack &S); Status DestoryStack(SqStack &S); bool StackEmpty(SqStack S); int StackLength(SqStack S); Status GetTop(SqStack S, int &e); Status Push(SqStack &S, int e); Status Pop(SqStack &S, int &e); Status StackTraverse(SqStack S, Status (*visit)(int)); Status visit(int e); int main() { int i, e; SqStack S; printf("初始化\n"); InitStack(S); printf("压栈:\n"); for (i = 0; i < 5; i++) { printf("输入e:"); scanf("%d", &e); Push(S, e); } printf("弹栈:"); Pop(S, e); printf("%d\n", e); printf("栈长:%d\n", StackLength(S)); printf("取栈顶元素:"); GetTop(S, e); printf("%d\n", e); printf("遍历栈:\n"); StackTraverse(S, visit); printf("清空栈:\n"); ClearStack(S); printf("是否为空栈:%d\n", StackEmpty(S)); printf("销毁栈:\n"); DestoryStack(S); return 0; } //初始化栈 Status InitStack(SqStack &S) { S.base = (int*)malloc(STACK_INIT_SIZE * sizeof(int)); if (!S.base) exit(OVERFLOW); S.top = S.base; S.stacksize = STACK_INIT_SIZE; return OK; } //清空栈 Status ClearStack(SqStack &S) { S.top = S.base; return OK; } //销毁栈 Status DestoryStack(SqStack &S) { free(S.base); S.base = NULL; S.top = NULL; S.stacksize = 0; return OK; } //是否是空栈 bool StackEmpty(SqStack S) { if (S.top == S.base) { return TRUE; } else { return FALSE; } } //栈长 int StackLength(SqStack S) { return S.top - S.base; } //取栈顶元素 Status GetTop(SqStack S, int &e) { if (S.top == S.base) { return ERROR; } e = *(S.top - 1); return OK; } //压栈 Status Push(SqStack &S, int e) { if (S.top - S.base >= S.stacksize) { S.base = (int*)realloc(S.base, (S.stacksize + STACKINCREMENT) * sizeof(int)); if (!S.base) { return OVERFLOW; } S.top = S.base + S.stacksize; S.stacksize += STACKINCREMENT; } *S.top = e; S.top ++; return OK; } //弹栈 Status Pop(SqStack &S, int &e) { if (S.top == S.base) { return ERROR; } e = *(S.top - 1); S.top--; S.stacksize--; return OK; } //遍历栈 Status StackTraverse(SqStack S, Status (* visit)(int)) { while (S.top > S.base) { visit(*S.base); S.base++; } return OK; } Status visit(int e) { printf("%d\n", e); return OK; }
数据结构——栈操作的实现
猜你喜欢
转载自www.cnblogs.com/HanLixiang/p/9821117.html
今日推荐
周排行