zoukankan      html  css  js  c++  java
  • C++ 泛型 编写的 数据结构 栈

    平时编程里经常需要用到数据结构,比如  栈和队列 等,  为了避免每次用到都需要重新编写的麻烦现将  C++ 编写的 数据结构   栈   记录下来,以备后用。

    将 数据结构  栈   用头文件的形式写成,方便调用。

    #ifndef STACK_CLASS
    #define STACK_CLASS
    
    #include<iostream>
    #include<cstdlib>
    using namespace std;
    const int MaxStackSize=50;
    
    //栈类的说明
    template <class T>
    class Stack
    {
    private:
        T stacklist[MaxStackSize];
        int top;
    
    public:
        Stack(void);
    
        void Push(const T &item);
        T Pop(void);
        void ClearStack(void);
        //访问栈顶元素
        T Peek(void) const;
    
        int StackLength(void) const;
        int StackEmpty(void) const;
        int StackFull(void) const;
    };
    
    //默认构造函数
    template <class T>
    Stack<T>::Stack(void):top(-1)
    {}
    
    template <class T>
    void Stack<T>::Push(const T &item)
    {
        if(top==MaxStackSize-1)
        {
            cerr<<"Stack overflow!"<<endl;
            exit(1);
        }
        top++;
        stacklist[top]=item;
    }
    
    template <class T>
    T Stack<T>::Pop(void)
    {
        T temp;
        if(top==-1)
        {
            cerr<<"Attempt to pop an empty stack"<<endl;
            exit(1);
        }
        temp=stacklist[top];
        top--; 
        return temp; 
    }
    
    template <class T>
    T Stack<T>::Peek(void) const
    {
        if(top==-1)
        {
            cerr<<"Attempt to peek at an empty stack"<<endl;
            exit(1);
        }
        return stacklist[top];
    }
    
    template <class T>
    int Stack<T>::StackLength(void) const
    {
        return top+1;
    }
    
    template <class T>
    int Stack<T>::StackEmpty(void) const
    {
        return top==-1;
    }
    
    template <class T>
    int Stack<T>::StackFull(void) const
    {
        return top==MaxStackSize-1;
    }
    
    template <class T>
    void Stack<T>::ClearStack(void)
    {
        top=-1;
    }
    #endif

    具体的调用形式:

    运行结果:

  • 相关阅读:
    mysql安装部署
    SSH升级
    符号、特殊字符的英文读法
    用python开发视频压缩器
    VSCode配置项
    工厂模式(简单工厂模式,工厂方法模式,抽象工厂模式)
    单例模式
    Jquery 绑定事件
    中文分词 新建索引 更新索引
    微信自动回复机器人
  • 原文地址:https://www.cnblogs.com/devilmaycry812839668/p/6351280.html
Copyright © 2011-2022 走看看