C++8/30——模仿模板库写栈和队列

stack

#include <iostream>

using namespace std;
#define MAX 20
template<typename T>
class Mystack
{
private:
    int top;
    //T *data;
    T data[20];
public:
//    Mystack(int size=MAX){
//        top=-1;
//        data=new T[size];
//    }
    Mystack(){
        top=-1;
    }
    void push(T a)
    {
        this->top++;
        this->data[top]=a;

    }
    void show()
    {
        for(int i=0;i<=top;i++)
        {
            cout<<data[i]<<" ";
        }cout<<endl;
    }
    void pop()
    {
        this->top--;
    }

    bool empty()
    {
        return top==-1?true:false;
    }
    bool full()
    {
        return top==(MAX-1)?true:false;
    }
};

int main()
{
    cout << "Hello World!" << endl;
    Mystack<int> s1;
    for(int i=0;i<10;i++)
    {
        s1.push(i);
    }
    s1.show();
    s1.pop();
    s1.show();
    cout<<"empty? "<<boolalpha<<s1.empty()<<endl;
    cout<<"full? "<<boolalpha<<s1.empty()<<endl;
    //cout<<s1.data[2]<<endl;
    return 0;
}

queue

#include <iostream>

using namespace std;
#define MAX 20
template<typename T>
class Myqueque
{
private:
    T data[MAX];
//    int front;
//    int tail;
    T *front;
    T *tail;
public:
    Myqueque(){
//        front=0;
//        tail=0;
        front=new T(0);
        tail=new T(0);
    }
    bool empty()
    {
        return front==tail?true:false;
    }
    bool full()
    {
        return (*tail+1)%MAX==*front?true:false;
    }
    void push(T a)
    {
        if(this->full())
            return;
        data[*tail]=a;
        *tail=(*tail+1)%MAX;
    }
    void show()
    {
        for(int i=*front;i!=*tail;i=(i+1)%MAX)
        {
            cout<<data[i]<<" ";
        }cout<<endl;
    }
    void pop()
    {
        *front=(*front+1)%MAX;
    }
};

int main()
{
    cout << "Hello World!" << endl;
    Myqueque<int> q1;
    for(int i=0;i<5;i++)
    {
        q1.push(i);
    }
    q1.show();
    q1.pop();
    q1.show();
    cout<<"empty? "<<boolalpha<<q1.empty()<<endl;
    cout<<"full? "<<boolalpha<<q1.empty()<<endl;
    return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值