tsaiwn@magpie % gcc stkmain.c stk.c 
tsaiwn@magpie % ./a.out 
53 770 880 

tsaiwn@magpie % cat -n stk.c
     1 // stk.c -- CopyLeft by tsaiwn@csie.nctu.edu.tw
     2 // 堆疊(Stack) 與 佇列(Queue; 排隊)是資料結構中很重要也很簡單的兩個
     3 // 線性資料結構!
     4 // 以下例子主要在說明如何在純種 C 語言中實作出一個堆疊 (Stack),
     5 //至於堆疊的定義以及用途請參考計概課本或是資料結構課本,
     6 //或者用 google.com 找一找應該也可看到許多實例與說明 :-)
     7 // 注意何以變數要 static ?  
     8 // ==> only can see by functions in this File  ==> Information hiding!
     9 //#define NELEMENT 99     // OK
    10    enum{NELEMENT=99};     // better
    11    static int data[NELEMENT];    // why static ?
    12    static int stkptr = -1;      // stack is empty
    13 // 以下三個函數宣告可有可無
    14       void push(int);
    15       void pop(void);
    16       int top(void);
    17 //////
    18 void push(int x) {
    19     stkptr++;
    20     data[stkptr] = x;
    21 }  
    22 int top(void) {
    23     return data[stkptr];
    24 }
    25 void pop(void) {
    26     if(stkptr> -1) --stkptr;
    27 }
    28 int empty(void){ return (stkptr <= -1) ;}
    29 int isfull(void){ return (stkptr >= NELEMENT-1);}
tsaiwn@magpie % cat -n stkmain.c
     1 // stkmain.c --- 使用 stk.c 中的堆疊 (Stack)
     2 // gcc stkmain.c stk.c   ;  ./a.out
     3 ///
     4 // 問題與考慮: 如果需要兩個 stack 要怎麼做?
     5 // 答案: 較簡單方法是把stk.c複製到另一file, 修改function name例如push2/pop2
     6 // 因為各file中變數有 static 保護, 不會被其它 file 中的 functions 看到!
     7 #include<stdio.h>
     8 int main( ){
     9    push(880);
    10    push(770);
    11    push(53);
    12    while(!empty()){
    13       printf("%d ", top( ) );
    14       pop();
    15    }
    16    printf("\n");
    17 }
tsaiwn@magpie % gcc stkmain.c stk.c
tsaiwn@magpie % ./a.out
53 770 880 

tsaiwn@magpie % exit
exit