问题遇到的现象和发生背景
用vs怎么写栈的定义
用代码块功能插入代码,请勿粘贴截图
#include<iostream>
using namespace std;
#define MaxSize 100//栈的最大容量
//顺序栈定义
struct SeqStack
{
int data[MaxSize];//存放栈元素的数组
int top;//栈顶指针
};
运行结果及报错内容
数组表达式必须为常数
用vs怎么写栈的定义
#include<iostream>
using namespace std;
#define MaxSize 100//栈的最大容量
//顺序栈定义
struct SeqStack
{
int data[MaxSize];//存放栈元素的数组
int top;//栈顶指针
};
数组表达式必须为常数
#define MaxSize 100 // 栈中元素的最大个数
#include <cstdlib>
#include <iostream>
#include <string>
using namespace std;
typedef int ElemType;
struct SqStack {
ElemType data[MaxSize]; // 静态数组存放栈顶元素
int top; // 栈顶指针
};
// 初始化栈
void InitStack(SqStack &S) { S.top = -1; }
// 判断栈空
bool StackEmpty(SqStack S) {
if (S.top == -1) {
return true;
} else {
return false;
}
}
// 入栈
bool Push(SqStack &S, ElemType x) {
if (S.top == MaxSize - 1) {
return false;
} else {
S.top++;
S.data[S.top] = x; // S.top指向栈顶
return true;
}
}
// 出栈
bool Pop(SqStack &S, ElemType &x) {
if (S.top == -1) { // 栈空
return false;
} else {
x = S.data[S.top--]; // 先赋值再--
return true;
}
}
// 读取栈顶元素
bool GetTop(SqStack S, ElemType &x) {
if (S.top == -1) {
return false;
} else {
x = S.data[S.top];
return true;
}
}
bool DestroyStack(SqStack &S) { S.top = -1; }
int main() {
SqStack S;
InitStack(S); // 初始化
cout << "栈是否为空:" << StackEmpty(S) << endl; // 判空
for (int i = 0; i < 5; i++) {
Push(S, i);
}
ElemType top, pop;
GetTop(S, top);
cout << "栈顶元素:" << top << endl;
Pop(S, pop);
cout << "出栈元素:" << pop << endl;
GetTop(S, top);
cout << "新栈顶元素:" << top << endl;
DestroyStack(S); // 销毁栈
cout << "栈是否为空:" << StackEmpty(S) << endl; // 判空
}