/* 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!\n"); else printf("value: %d\n", popSeqStack(s)); break; case 3: if(isEmptySeqStack(s)) printf("SeqStack is empty!\n"); else printf("value: %d\n", 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]; }
