頭文件
Seqstack.h
#define maxsize 6 //const int maxsize = 6; // 順序棧 typedef struct seqstack { int data[maxsize]; int top; // 標志棧頂位置的變量 }SeqStk;
main.c
#include <stdio.h> #include "Seqstack.h" // 棧的基本運算在順序棧上的實現 // 1. 初始化 int InitStack(SeqStk *stk) { stk->top = 0; return 1; } // 2. 判斷棧空 int EmptyStack(SeqStk *stk) { if(stk->top == 0) return 1; else return 0; } // 3.進棧 int Push(SeqStk *stk, int x) { if(stk->top == maxsize - 1) { printf("棧已滿\n"); return 0; } else { stk->data[stk->top] = x; stk->top++; return 1; } } // 4. 出棧 int Pop(SeqStk *stk) { if(EmptyStack(stk)) { printf("下溢"); return 0; } else { stk->top--; return 1; } } // 5. 取棧頂元素 int GetTop(SeqStk *stk) { if(EmptyStack(stk)) return 0; else return stk->data[stk->top]; } main() { SeqStk stk; int i; i = InitStack(&stk); if(i) printf("初始化成功\n"); else printf("初始化失敗\n"); Push(&stk, 1); Push(&stk, 2); Push(&stk, 3); for(i = 0;i < 3;i++) printf("%d\n", stk.data[i]); printf("\n"); }
