資料結構——棧操作的實現
阿新 • • 發佈:2018-11-09
#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; }