数据结构——栈

本文介绍了一个使用C++和数组实现的栈数据结构。该栈包括基本操作如压栈、弹栈、获取栈顶元素等,并提供了测试代码示例。

一.利用C++、数组实现的栈

//Mystack.h

#include<iostream>
using namespace std;

//利用数组容器实现的一个栈
class Mystack{
private:
    int MAXSIZE=8;//设定最大容量
    int* a;//引用数组名
    int num;//栈顶在数组中的下标,下标始终指向下一个空位置,亦即使用容量大小
public:

    //构造函数创建数组容器
    Mystack(){
        a = new int[MAXSIZE];
        num = 0;
    }

    ~Mystack(){
        delete[] a;
    }

    //返回栈顶元素:栈空返回-1
    int top(){
        if (num == 0)
            return -1;
        return a[num - 1];
    }

    //弹出栈:栈空返回-1
    int pop(){
        if (num == 0){
            cout << "Empty" << endl;
            return -1;
        }
        num--;
        return a[num];
    }

    //将元素压入栈
    void push(int val){
        if (num == MAXSIZE){
            cout << "full" << endl;
            return;
        }    
        a[num] = val;
        num++;
    }

    //返回元素个数
    int size(){
        return num;

    }

    //是否满:1是0否
    bool isFull(){
        if (num == MAXSIZE)
            return true;
        return false;
    }

    //是否空:1是0否
    bool isEmpty(){
        if (num == 0)
            return true;
        return false;
    }
};
//test.cpp

#include<iostream>
#include"Mystack.h"
using namespace std;

//一些函数功能测试
void main(){

    Mystack ms;//创建一个栈


    cout <<"is Empty? "<< ms.isEmpty() << endl;

    cout << "is Full?" << ms.isFull() << endl;

    int a[] = { 1, 2, 3, 4, 5 };
    for (int i = 0; i < 5; i++){
        ms.push(a[i]);
    }
    cout  << "is Empty? "<<ms.isEmpty() << endl;
    cout << "have " << ms.size() <<" elements"<< endl;

    for (int i = 0; i < 5; i++){
        cout << ms.top() << endl;
        ms.pop();
    }
    
}

 

转载于:https://www.cnblogs.com/jizhji/p/5875785.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值