文章目录 1. 数据元素的表示2. 初始化栈3. 判断栈空4. 进栈操作5. 出栈操作6. 读栈顶元素7. 打印栈中元素 1. 数据元素的表示 #define MaxSize 10 // 定义栈中元素的最大个数 typedef struct { int data[MaxSize]; // 数据域 int top; // 栈顶指针 }SqStack; 2. 初始化栈 /* 初始化栈 */ bool InitStack(SqStack& S) { S.top = -1; // 初始化栈顶指针,指向栈顶元素 return true; } 3. 判断栈空 /* 判断栈空 */ bool StackEmpty(SqStack S) { if (S.top == -1) { // 栈为空 return true; } else { return false; // 栈不空 } } 4. 进栈操作 /* 进栈操作 */ bool Push(SqStack& S, int x) { if (S.top == MaxSize - 1) { // 栈已满,返回false return false; } else { // 栈未满或为空栈 S.data[++S.top] = x; // 指针先加一,再入栈(栈顶指针指向栈顶元素) return true; } } 5. 出栈操作 /* 出栈操作 */ bool Pop(SqStack& S, int &e) { if (S.top == -1) { // 空栈,返回false return false; } else { e = S.data[S.top--]; // 先出栈,指针再减一 return true; } } 6. 读栈顶元素 /* 读栈顶元素操作 */ bool GetTop(SqStack S, int& e) { if (S.top == -1) { // 栈空,返回false return false; } else { e = S.data[S.top]; return true; } } 7. 打印栈中元素 /* 打印栈中元素(由顶部到底部) */ void PrintOut(SqStack S) { if (S.top == -1) { // 空栈 printf("The SqStack(from top to bottom):null\n"); return; } printf("The SqStack(from top to bottom):"); for (int i = S.top; i >= 0; i--) { printf("%d ",S.data[i]); } printf("\n"); }