栈类(C++)

简介: 简介:通过题目的方式来介绍如何通过C++实现栈,通过理解栈的底层原理,来更好的学习这个数据结构。首先定义数据元素类型。

用C++实现栈

简介:通过题目的方式来介绍如何通过C++实现栈,通过理解栈的底层原理,来更好的学习这个数据结构
题目

请设计通用栈类。

首先定义数据元素类型

typedef double ELEMENT;
然后定义栈

class STACK
{
public:
    STACK();
    ~STACK();
    bool Push(const ELEMENT &value);
    bool Pop(ELEMENT &value);
    bool Clear();
    bool Empty() const;
    int Length() const;

    const static int stackSize;

private:
    int size, top;
    ELEMENT *element;
};

const int STACK::stackSize = 5;

说明:

  • size 为动态数组的尺寸,top 为栈顶元素的下标,element 为动态数组的起始地址。
  • stackSize 为动态数组的尺寸,初始值为 5。
  • 构造函数:初始化栈:将初始尺寸保存到 size,将栈顶下标 top 置为 -1,为动态数组分配内存并将起始地址保存到 element。
  • 析构函数:清理栈:释放动态数组的内存。
  • Push 函数:若栈未满,则将元素 value 保存到栈中,函数值为 true;否则报告上溢错误,函数值为 false。
  • Pop 函数:若栈不空,则从栈中取出元素并保存到 value中,函数值为 true;否则报告下溢错误,函数值为 false。
  • Clear 函数:清空栈,操作成功,函数值为 true。
  • Empty 函数:若栈空,则函数值为 true,否则为 false。
  • Length 函数:函数值为栈中元素的数量。

裁判程序

#include <iostream>
#include <iomanip>
using namespace std;
#include <cctype>

typedef double ELEMENT;

class STACK
{
public:
    STACK();
    ~STACK();
    bool Push(const ELEMENT &value);
    bool Pop(ELEMENT &value);
    bool Clear();
    bool Empty() const;
    int Length() const;

    const static int stackSize;

private:
    int size, top;
    ELEMENT *element;
};

const int STACK::stackSize = 5;

/* 你提交的代码将被嵌在这里 */

int main()
{
    STACK stack;
    ELEMENT value;
    char choice;
    do
    {
        cout << "Push pOp Clear Empty Length Quit > ";
        cin >> choice;
        choice = toupper(choice);
        
        switch (choice)
        {
        case 'P':
            cout << "Value: ";
            cin >> value;
            if (stack.Push(value))
            {
                cout << "Push successfully!\n";
            }
            else
            {
                cout << "Push failed!\n";
            }
            break;
        case 'O':
            if (stack.Pop(value))
            {
                cout << "Pop successfully!\n";
                cout << "Value: " << value << endl;
            }
            else
            {
                cout << "Pop failed!\n";
            }
            break;
        case 'C':
            if (stack.Clear())
            {
                cout << "Clear successfully!\n";
            }
            else
            {
                cout << "Clear failed!\n";
            }
            break;
        case 'E':
            if (stack.Empty())
            {
                cout << "Stack is empty!\n";
            }
            else
            {
                cout << "Stack is not empty!\n";
            }
            break;
        case 'L':
            cout << "Stack length: " << stack.Length() << endl;
            break;
        case 'Q':
            break;
        default:
            cout << "Incorrect choice!\n";
        }
    }
    while (choice != 'Q');
}

测试样例1

Push pOp Clear Empty Length Quit > t
Incorrect choice!
Push pOp Clear Empty Length Quit > K
Incorrect choice!
Push pOp Clear Empty Length Quit > Q

测试样例2

Push pOp Clear Empty Length Quit > L
Stack length: 0
Push pOp Clear Empty Length Quit > e
Stack is empty!
Push pOp Clear Empty Length Quit > P
Value: 4.5
Push successfully!
Push pOp Clear Empty Length Quit > p
Value: 1.6
Push successfully!
Push pOp Clear Empty Length Quit > l
Stack length: 2
Push pOp Clear Empty Length Quit > E
Stack is not empty!
Push pOp Clear Empty Length Quit > o
Pop successfully!
Value: 1.6
Push pOp Clear Empty Length Quit > O
Pop successfully!
Value: 4.5
Push pOp Clear Empty Length Quit > O
Stack underflow!
Pop failed!
Push pOp Clear Empty Length Quit > q

测试样例3

Push pOp Clear Empty Length Quit > p
Value: 0.5
Push successfully!
Push pOp Clear Empty Length Quit > p
Value: 1.7
Push successfully!
Push pOp Clear Empty Length Quit > p
Value: 2.8
Push successfully!
Push pOp Clear Empty Length Quit > p
Value: 3.6
Push successfully!
Push pOp Clear Empty Length Quit > p
Value: 4.9
Push successfully!
Push pOp Clear Empty Length Quit > p
Value: 9.9
Stack overflow!
Push failed!
Push pOp Clear Empty Length Quit > L
Stack length: 5
Push pOp Clear Empty Length Quit > e
Stack is not empty!
Push pOp Clear Empty Length Quit > C
Clear successfully!
Push pOp Clear Empty Length Quit > l
Stack length: 0
Push pOp Clear Empty Length Quit > E
Stack is empty!
Push pOp Clear Empty Length Quit > p
Value: 8.5
Push successfully!
Push pOp Clear Empty Length Quit > O
Pop successfully!
Value: 8.5
Push pOp Clear Empty Length Quit > q

输出样例
Push pOp Clear Empty Length Quit >

输入样例
q

代码长度限
16 KB
时间限制
400 ms
内存限制
64 MB

题解:

STACK::STACK()
{
    size = stackSize;
    top = -1;
    element = new ELEMENT[size];      // 这里是c++程序 所以不能使用C语言的malloc和free函数因为new函数是每个元素都要构造的 但是malloc不会
}

STACK::~STACK()
{
    delete []element; // 释放资源
}
bool STACK::Push(const ELEMENT &value)
{
    if (top + 1 >= this->size) // 首先判断一下是否栈满了
    {
        cout << "Stack overflow!\n"; // 如果栈满了就需要输出Stack overflow!
        return false ; // 返回入栈失败
    }
    this->element[++top] = value; // 反之插入栈顶
    return true;
}
int STACK::Length() const // 因为初始值是top = -1所以返回长度的时候需要top+1
{
    return top + 1;
}

bool STACK::Pop(ELEMENT &value)
{
    if (top == -1) // 先判断栈是否为空
    {
        cout << "Stack underflow!\n";
        return false;
    }
    value = this->element[top--]; // 不为空的出栈第一个元素 然后top - 1
    return true;
}
bool STACK::Clear()  // 通过把top置为-1的方式快速清空栈
{
    // if (top == -1) return false; 
    top = -1;
    return true;
}
bool STACK::Empty() const // 如果top=-1那么栈为空
{
    return top == -1;
}
相关文章
|
1天前
|
监控 网络协议 算法
2026年起SSL证书有效期逐年缩短:企业如何避免“续期风暴”!
SSL证书有效期将从2026年起分三阶段逐步缩短至47天,人工续期难以为继。阿里云“WoSign SSL证书+自动化服务”,支持域名监控、自动托管、云产品/服务器一键部署及智能提醒,助力企业高效应对高频续期挑战。
8045 0
|
10天前
|
域名解析 人工智能 Linux
|
20天前
|
Linux Go 开发工具
手机上跑 DeepSeek 智能体:开源安卓客户端 DSH Go 安装与使用指南
DSH Go 是一款开源安卓客户端,将 DeepSeek Harness 智能体引擎装进手机:免 Root、免 Termux,一键安装即用;支持本机运行(内置 Ubuntu+Node.js)或远程接管电脑会话;具备插话打断、过程折叠、屏幕操控、端到端加密分享等特色功能,真正实现智能体“口袋化”。
17957 63
|
18天前
|
人工智能
Google 提示「所在地区不可用」?进不去 Antigravity 或 Gemini,先查账号这个设置
进不去 Antigravity 或 Gemini,提示所在地区不可用?三步查清 Google 账号关联地区、官方更正表单理由选法与改区注意事项。
Google 提示「所在地区不可用」?进不去 Antigravity 或 Gemini,先查账号这个设置
|
4天前
|
人工智能 安全 网络安全
|
1天前
|
人工智能 弹性计算 安全
阿里云 码上2027 AI coding 嘉年华
阿里云“码上2027”AI Coding嘉年华于2026年12月2—3日在上海西岸艺术中心举行,聚焦AI Coding从单点提效迈向企业级研发体系升级。发布Qwen4-max模型、QBot智能协作、AgentCore平台等重磅成果,并推出ECS云服务器特惠(200Mbps流量月付40元起)。
757 0
|
7天前
|
云安全 数据采集 人工智能
|
9天前
|
Linux API iOS开发
【DSH】DeepSeek Harness新手保姆教程(下载+安装+配置+使用,2026最新实测)
DeepSeek Harness(dsh)是 DeepSeek AI 开源的智能体框架,秉持“一切皆插件”理念,支持读文件、改代码、执行命令、处理表格等自动化任务;免费开源,兼容 Win/macOS,需配 API 密钥使用。(239字)
1445 5
|
15天前
|
人工智能 开发工具 开发者
2026最新codex下载安装保姆级使用教程(下载+安装+登录+使用,含所有历史版本)
Codex 是 OpenAI 推出的开源 AI 编程智能体,跑在本地终端和桌面客户端里,能读懂整个代码仓库,一句自然语言就能让它改代码、执行命令、跑测试、修 Bug,支持 Windows、macOS、Linux 三大平台。本文把 Codex下载、安装、登录、汉化、基础使用一次讲全,并整理了国内用户最常踩的坑,跟着做 10 分钟就能跑起来。
2547 8
|
20天前
|
弹性计算 人工智能 API
Codex超详细入门指南(下载·安装·登录·上手,全版本覆盖,2026最新版)
建议收藏本教程,2026 全年各版本更新随时回来查阅。如果你在搭建过程中遇到任何问题,欢迎结合 阿里云工单系统 提交技术支持请求,或在 阿里云开发者社区 搜索 Codex 相关话题交流。 祝你编码愉快,效率翻倍!
4043 22