• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
慧眼识猪
博客园    首页    新随笔    联系   管理    订阅  订阅

数据结构——栈

一.利用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();
    }
    
}

 

posted @ 2016-09-16 01:15  慧眼识猪  阅读(212)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3