1. 程式人生 > >資料結構——靜態順序棧的基本操作

資料結構——靜態順序棧的基本操作

程式碼主要來源:【資料結構】【清華大學】【嚴蔚敏】
/程式碼背景是基於書上的,可內容確實是自己理解後敲的,這不禁讓人思考(糾結)原創的定義了/
順序棧S的基本運算如下:
(1)初始化棧S
(2)棧為空
(3)依次進棧元素a,b,c,d,e
(4)棧為非空
(5)出棧序列:e d c b a
(6)棧為空
(7)釋放棧
//本題靜態棧,不用有釋放空間的步驟,非要釋放可以用memset(a,0,MAXSIZE)表示

//這個靜態順序棧(約等於是陣列)可能是棧和佇列型別中最簡單的

#include <stdio.h>
#include <stdlib.h>
#define
OK 1
#define ERROR 0 #define OVERFLOW -1 #define TRUE 1 #define FALSE 0 #define MAXSIZE 100 typedef struct Stack { char data[MAXSIZE]; // 棧 int top; // 棧頂指標(實際是陣列的下標值) } SqStack; int InitStack(SqStack &S) { S.top=0; } int Push(SqStack &S,char e) { if(S.top>=
MAXSIZE) return ERROR; S.data[S.top++]=e; return OK; } int Pop(SqStack &S,char &e) { if(S.top == 0) return ERROR; e=S.data[--S.top];//e=*(S.data+S.top-1) return OK; } int Empty(SqStack &S) { if(S.top == 0) return 1; else return 0; } int main() { SqStack S; char a[5]= {'a','b','c'
,'d','e'},e; InitStack(S); if(Empty(S)) { printf("棧為空\n"); } for(int i=0; i<5; i++) { Push(S,a[i]); } if(!Empty(S)) { printf("棧非空\n"); } while(!Empty(S)) { Pop(S,e); printf("%c ",e); } if(Empty(S)) { printf("\n棧為空\n"); } }