1 #define MaxSize 100 2 3 //順序棧的創建 4 typedef struct { 5 int *base;//棧底指針 6 int *top;//棧頂指針 7 int stacksize;//棧可用最大容量 8 }SqStack; 9 10 //棧的初始化 11 bool InitStack(SqStack &s) 12 { 13 s.base = new int[MaxSize]; 14 //s.base = (int*)malloc(StackMaxSize*sizeof(int)); 15 if (!s.base)//判斷分配內存有沒有成功 16 return false; 17 s.top = s.base; 18 s.stacksize = MaxSize; 19 return true; 20 } 21 22 //判棧空 23 bool StackEmpty(SqStack s) 24 { 25 if (s.base == s.top) 26 return true; 27 else 28 return false; 29 } 30 31 //求棧長 32 int StackLength(SqStack s) 33 { 34 return s.top - s.base; 35 } 36 37 //清空順序棧 38 bool StackClear(SqStack &s) 39 { 40 if (s.base) 41 s.top = s.base;//直接將top下移下來就可 42 return true; 43 } 44 45 //銷毀順序棧 46 bool StackDestroy(SqStack &s) 47 { 48 if (s.base) { 49 delete s.base;//釋放指針內存,和new配對,指針的對象沒了 50 s.stacksize = 0;//將棧的個數設置為0 51 s.base = s.top = NULL;//避免野指針生成 52 } 53 return true; 54 } 55 56 //入棧操作---存放元素到棧頂 57 bool PushStack(SqStack &s, int e) 58 { 59 //棧底永遠在下面呢---判斷棧滿了 60 if (s.top - s.base == s.stacksize) 61 return false; 62 63 *s.top = e;//元素e壓入棧頂 64 s.top++;//棧指針+1 65 return true; 66 } 67 68 //出棧操作---將位於棧頂的元素彈出 69 bool PopStack(SqStack &s, int &e) 70 { 71 //判斷指針下溢 72 if (s.base == s.top) 73 return false; 74 e = *s.top; 75 s.top--; 76 }