fangfei1314 2022-10-12 09:52 采纳率: 77.8%
浏览 16
已结题

用vs怎么写栈的定义

问题遇到的现象和发生背景

用vs怎么写栈的定义

用代码块功能插入代码,请勿粘贴截图
#include<iostream>
using namespace std;
#define MaxSize 100//栈的最大容量
//顺序栈定义
struct SeqStack
{
    int data[MaxSize];//存放栈元素的数组
    int top;//栈顶指针
};
运行结果及报错内容

数组表达式必须为常数

  • 写回答

1条回答 默认 最新

  • 快乐鹦鹉 2022-10-12 10:06
    关注
    #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; // 判空
    }
    
    
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

问题事件

  • 系统已结题 10月20日
  • 已采纳回答 10月12日
  • 创建了问题 10月12日

悬赏问题

  • ¥15 ETLCloud 处理json多层级问题
  • ¥15 matlab中使用gurobi时报错
  • ¥15 这个主板怎么能扩出一两个sata口
  • ¥15 不是,这到底错哪儿了😭
  • ¥15 2020长安杯与连接网探
  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么
  • ¥15 banner广告展示设置多少时间不怎么会消耗用户价值
  • ¥15 可见光定位matlab仿真
  • ¥15 arduino 四自由度机械臂
  • ¥15 wordpress 产品图片 GIF 没法显示