栈类(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;
}
相关文章
|
存储 JSON 固态存储
【离线】esrally实践总结
1.真正的离线安装esrally 2.术语介绍,官方数据集、track介绍 3.官方数据集下载 4.离线使用esrally测试现有ES测试集群 5.对比两次race(测试)的结果 6.测试时间太长怎么办? 7.报告分析
3375 2
【离线】esrally实践总结
|
10月前
|
芯片
MCU最小系统电路设计(以STM32F103C8T6为例)-1
MCU最小系统电路设计(以STM32F103C8T6为例)
MCU最小系统电路设计(以STM32F103C8T6为例)-1
|
5月前
|
机器学习/深度学习 数据采集 人工智能
揭开大模型幻觉之谜:深入剖析数据偏差与模型局限性如何联手制造假象,并提供代码实例助你洞悉真相
【10月更文挑战第2天】近年来,大规模预训练模型(大模型)在自然语言处理和计算机视觉等领域取得卓越成绩,但也存在“大模型幻觉”现象,即高准确率并不反映真实理解能力。这主要由数据偏差和模型局限性导致。通过平衡数据集和引入正则化技术可部分缓解该问题,但仍需学界和业界共同努力。
85 4
|
9月前
|
Java API 开发工具
企业微信api,企业微信sdk接口java调用源码
企业微信api,企业微信sdk接口java调用源码
|
5月前
|
Kubernetes Cloud Native Docker
云原生时代的容器化实践:Docker与Kubernetes入门
【9月更文挑战第30天】在云计算的浪潮中,云原生技术正以前所未有的速度重塑着软件开发和运维领域。本文将通过深入浅出的方式,带你了解云原生的核心组件——Docker容器和Kubernetes集群,并探索它们如何助力现代应用的构建、部署和管理。从Docker的基本命令到Kubernetes的资源调度,我们将一起开启云原生技术的奇妙之旅。
|
7月前
|
负载均衡 算法 Java
SpringCloud之Ribbon使用
通过 Ribbon,可以非常便捷的在微服务架构中实现请求负载均衡,提升系统的高可用性和伸缩性。在实际使用中,需要根据实际场景选择合适的负载均衡策略,并对其进行适当配置,以达到更佳的负载均衡效果。
265 13
|
算法
算法有穷性
算法有穷性
347 2
|
9月前
|
存储 双11 云计算
云计算的前世今生来世(一)
云计算历经四阶段:从大型机到个人电脑,再到互联网和云计算革命。它主要解决计算、网络、存储和应用问题。计算发展表现为“分合分”的模式:物理设备、虚拟化、云计算及容器化。如今,云计算已渗透到生活各个方面,包括工业、日常交易如双十一购物节,以及办公、社交应用等。技术路径涵盖IaaS(计算、网络、存储)和PaaS(应用)层面。
|
10月前
|
JavaScript 前端开发 API
Vue 3.0 v-for中的Ref数组
Vue 3.0 v-for中的Ref数组
165 0
|
10月前
|
vr&ar Python
Python ARIMA时间序列模型预测航空公司的乘客数量
Python ARIMA时间序列模型预测航空公司的乘客数量