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

     顺序栈类模板实现

    这是头文件seqStack.h

    //seqStack.h
    #ifndef SEQSTACK_H_INCLUDED
    #define SEQSTACK_H_INCLUDED
    #include <iostream>
    using namespace std;
    template<class T>
    class seqStack
    {
    public:
        seqStack();
        seqStack(int num);
        bool empty()const;
        void pop();
        void push(const T &x);
        int size()const;
        const T&top()const;
        void print()const;
    private:
        int MAX_LENGTH;
        T *data;
        void init();
        int iTop;
    
    };
    
    template<class T>
    seqStack<T>::seqStack():MAX_LENGTH(100)
    {
        init();
    }
    
    template<class T>
    seqStack<T>::seqStack(int num):MAX_LENGTH(num)
    {
        init();
    }
    
    template<class T>
    void seqStack<T>::init()
    {
        data=new T[MAX_LENGTH];
        iTop=-1;
    }
    template<class T>
    bool seqStack<T>::empty()const
    {
        return iTop==-1;
    }
    
    template<class T>
    void seqStack<T>::pop()
    {
        if(iTop>-1)
            iTop--;
    }
    
    template<class T>
    void seqStack<T>::push(const T&x)
    {
        if(iTop==MAX_LENGTH-1)
        {
            cout<<"Stack is fulled"<<endl;
            return ;
        }
        iTop++;
        data[iTop]=x;
    }
    
    template<class T>
    int seqStack<T>::size()const
    {
        return iTop+1;
    }
    
    template<class T>
    const T&seqStack<T>::top()const
    {
        if(iTop>-1)
            return data[iTop];
        cout<<"stack is empty"<<endl;
        T t;
        return t;
    }
    template<class T>
    void seqStack<T>::print()const
    {
        for(int i=0;i<=iTop;i++)
        {
            cout<<data[i]<<" ";
        }
        cout<<endl;
    }
    
    #endif // SEQSTACK_H_INCLUDED

     这是一个示例

    #include"seqStack.h"
    using namespace std;
    
    int main()
    {
        seqStack<int> s;
        s.push(1);
        s.push(7);
        s.print();
        s.print();
        s.push(2);
        s.print();
        cout<<s.top()<<endl;
        s.pop();
        s.print();
        s.pop();
        s.print();
        s.pop();
        s.print();
        return 0;
    }

     运行截图

     

  • 相关阅读:
    Kubernetes List-Watch
    Go 模板语法
    vRA7 Business error “Untrusted certificate chain”
    Centos 7/8 安装 Harbor
    Kubernetes Headless Service
    Kubernetes addon-manager
    Kubernetes Metrics-Server
    Kubernetes Heapster
    容器rootfs
    Kubernetes lxcfs
  • 原文地址:https://www.cnblogs.com/hjw1/p/7914230.html
Copyright © 2011-2022 走看看