C++编译器
#include <stdio.h>
#define INITSTACKSTATUS -1
#define MAXSIZE 10
#define NAN -999999
struct SqStack {
int data[MAXSIZE];
int top;
/*
初始化栈
*/
void initStack() {
this->top = INITSTACKSTATUS;
}
/*
将元素值压入栈中
arg1:将要压入栈中的目标元素值
return true:压入成功 false:压入失败
*/
bool push(int value) {
if (top >= MAXSIZE) {
printf("this SqStack is full,can not push\n");
return false;
}
this->data[++this->top] = value;
return true;
}
/*
弹出栈顶部元素值
*/
int pop() {
if (this->isEmpty()) {
printf("this SqStack is empty,can not pop top value\n");
return NAN;
}
return this->data[this->top--];
}
/*
获取栈顶部元素值
*/
int getTop() {
if (this->isEmpty()) {
printf("this SqStack is empty,can not get top value\n");
return NAN;
}
return this->data[this->top];
}
/*
判断栈是否为空
*/
bool isEmpty() {
return this->top == INITSTACKSTATUS;
}
void print() {
for (int i = this->top; i > INITSTACKSTATUS; i--) {
printf("%d ", this->data[i]);
}
printf("lenth=%d\n", this->top + 1);
}
};
int main() {
SqStack sqStack;
sqStack.initStack();
printf("this SqStack is Empty:%s\n", sqStack.isEmpty() ? "true" : "false");
for (int i = 0; i < 5; i++) {
sqStack.push(i);
}
printf("this SqStack is Empty:%s\n", sqStack.isEmpty() ? "true" : "false");
sqStack.print();
printf("this SqStack top value is %d\n", sqStack.getTop());
sqStack.print();
sqStack.pop();
sqStack.pop();
sqStack.print();
return 0;
}
运行截图: