zoukankan      html  css  js  c++  java
  • C++实现顺序栈类

      堆栈(英文:stack),也可直接称栈。在计算机科学中,栈是一种特殊的串行形式的数据结构,它的特殊之处在于只能允许在链结串行或阵列的一端(称为堆栈顶端指标,英文为top)进行加入资料(push)和输出资料(pop)的运算。

      另外堆栈也可以用一维阵列或连结串行的形式来完成。

      由于堆栈数据结构只允许在一端进行操作,因而按照后进先出(LIFO, Last In First Out)的原理运作。

      堆栈数据结构使用两种基本操作:推入(push)和弹出(pop)。

    头文件
    #ifndef sq_stack_h
    #define sq_stack_h
    
    #define STACK_INIT_SIZE 10 //初始栈的最大长度
    #define STACKINCREMENT 10 //每次新增的栈的长度
    
    template <class DataType>
    class sq_stack{
    public:
        sq_stack();
        void Push(DataType e); //插入为e的新栈顶元素
        void Pop(); //删除栈顶元素
        DataType Top(); //取出栈顶元素
        bool Empty(); //判断栈是否为空:空返回1
        ~sq_stack(); //栈被销毁
    
    private:
        DataType *base; //栈尾
        DataType *top; //栈顶
        int stacksize;
    };
    #endif
    源文件以及测试代码
    #include "sq_stack.h"
    #include <iostream>
    
    using namespace std;
    
    template <class DataType>
    sq_stack<DataType>::sq_stack()
    {
        base = new DataType[STACK_INIT_SIZE];
        if(!base) exit(1);
        top=base;
        stacksize=STACK_INIT_SIZE;
    }
    
    template <class DataType>
    void sq_stack<DataType>::Push(DataType e)
    {
        if(top-base>=stacksize-1){
            base=(DataType*)realloc(base,(stacksize+STACKINCREMENT)*sizeof(DataType));
            if(!base) exit(1);
            top=base+stacksize-1;
            stacksize+=STACKINCREMENT;
        }
        *top++=e;
    }
    
    template <class DataType>
    void sq_stack<DataType>::Pop()
    {
        if(top==base) exit(1);
        top--;
    }
    
    
    template <class DataType>
    DataType sq_stack<DataType>::Top()
    {
        if(top==base) return NULL;
        return *(top-1);
    }
    
    
    template <class DataType>
    bool sq_stack<DataType>::Empty()
    {
        return top==base? 1:0;
    }
    
    template <class DataType>
    sq_stack<DataType>::~sq_stack()
    {
        if(base) free(base);
        top = base = NULL;
        stacksize = 0;
    }
    
    int main()
    {
        sq_stack<int> st;
        for(int i=1;i<=20;i++)
            st.Push(i);
        for(int i=1;i<=20;i++)
        {
            cout<<st.Top()<<" ";
            st.Pop();
            if (i%5 == 0){cout<<endl;}
        }
        system("pause");
        return 0;
    }
  • 相关阅读:
    AOSP 设置编译输出目录
    android stadio 编译报错:download fastutil-7.2.0.jar
    Ubuntu adb 报错:no permissions (user in plugdev group; are your udev rules wrong?);
    Ubuntu 18启动失败 Started Hold until boot procss finishes up
    算法---------两数之和
    Windows 显示环境变量
    Android ObjectOutputStream Serializable引发的血案
    (AOSP)repo checkout指定版本
    如果看懂git -help
    Android stado 运行项目,apk does not exist on disk.
  • 原文地址:https://www.cnblogs.com/wentfar/p/2737370.html
Copyright © 2011-2022 走看看