/* sequenceStack.c */ /* 栈 先进后出(First In Last Out,FILO)*/ #include <stdio.h> #include <stdlib.h> #include <stdbool.h> #define MAXSIZE 100 /* 栈数据结构 */ /* —————————— | data[2] | <--- top ——————————— | —————————— | data[1] | ——————————— | —————————— | data[0] | ——————————— */ typedef struct { int data[MAXSIZE]; /* 数组 */ int top; /* 栈指针 0表示栈底,-1表示空栈 */ } SeqStack; /* 栈函数声明 */ void interface(void); SeqStack *initializeSeqStack(); bool isEmptySeqStack(SeqStack*); int pushSeqStack(SeqStack*, int); int popSeqStack(SeqStack*); int peekSeqStack(SeqStack*); /* 程序主函数入口 */ int main(){ SeqStack *s = initializeSeqStack(); int flag, number; interface(); for(;;){ printf("Command: "); scanf("%d", &flag); switch(flag){ case 0: return 0; break; case 1: printf("Enter number: "); scanf("%d", &number); pushSeqStack(s, number); break; case 2: if(isEmptySeqStack(s)) printf("SeqStack is empty! "); else printf("value: %d ", popSeqStack(s)); break; case 3: if(isEmptySeqStack(s)) printf("SeqStack is empty! "); else printf("value: %d ", peekSeqStack(s)); break; } } return 0; } /* 用户界面 */ void interface(void){ puts("+*********************************+"); puts("+ 0, quit 退出 +"); puts("+ 1, push 压入 +"); puts("+ 2, pop 弹出 +"); puts("+ 3, peek 查看 +"); puts("+*********************************+"); } /* 栈函数实现 */ /* 初始化栈 */ SeqStack *initializeSeqStack(){ SeqStack *s = (SeqStack*)malloc(sizeof(SeqStack)); s->top = -1; return s; } /* 判断栈是否为空 */ bool isEmptySeqStack(SeqStack *s){ if(s->top==-1){ return true; } return false; } /* 入栈 */ int pushSeqStack(SeqStack *s, int num){ /* 栈满不能入栈 */ if(s->top==MAXSIZE-1){ return 1; }else{ s->data[++s->top] = num; return 0; } } /* 出栈 */ int popSeqStack(SeqStack *s){ return s->data[s->top--]; } /* 取栈顶元素 */ int peekSeqStack(SeqStack *s){ return s->data[s->top]; }