首页 > 其他 > 详细

数据结构——栈

时间:2016-09-16 01:38:57      阅读:245      评论:0      收藏:0      [点我收藏+]

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

 

数据结构——栈

原文:http://www.cnblogs.com/jizhji/p/5875785.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!