8月30日C++作业

手动用C++封装一个栈和队列

#include <iostream>

using namespace std;
#define MAX 8
template <typename T>
class zhan
{
private:
    int top;
    T arr[MAX];
public:
    zhan():top(-1){}
    ~zhan(){}
    bool pankong()
    {
        return this->top == -1;
    }
    bool panman()
    {
        return this->top == MAX-1;
    }
    int ruzhan(const T other)
    {
        if(panman())
            throw -1;
        this->top++;
        arr[top] = other;
        return 0;
    }
    int chuzhan()
    {
        if(pankong())
            throw -1;
        cout<<arr[top]<<endl;
        this->top--;
        return 0;
    }
    zhan(const zhan& other)
    {
        this->top = other.top;
        for(int i=this->top; i>-1; i--)
        {
            this->arr[i] = other.arr[i];
        }
    }
    void show()
    {
        cout<<"从栈顶到栈底的元素为:";
        int i = 0;
        for(i=this->top; i>-1; i--)
        {
            cout<<arr[i]<<"  ";
        }
        cout<<endl;
    }
};
int main()
{
    zhan<int> s1;
    for(int i=1; i<=8; i++)
    {
       try{ s1.ruzhan(i);
        }catch(int n)
        {
            if(-1 == n)
                cout<<"栈已经满了,入栈失败"<<endl;
        }
    }
    s1.show();
    s1.chuzhan();
    s1.show();
    cout<<s1.pankong()<<endl;
    cout<<s1.panman()<<endl;

    zhan<int> s2 = s1;
    s2.show();

    return 0;
}

 

#include <iostream>

using namespace std;
#define MAX 8
template<typename T>
class duilie
{
private:
    T arr[MAX];
    int front;
    int tail;
public:
    duilie():front(0),tail(0){}
    ~duilie(){}
    bool pankong()
    {
        return front == tail;
    }
    bool panman()
    {
        return (tail+1)%MAX == front;
    }
    int rudui(const T other)
    {
        if(panman())
            throw -1;
        this->arr[tail] = other;
        this->tail = (this->tail+1)%MAX;
        return 0;
    }
    int chudui()
    {
        if(pankong())
            throw -2;
        cout<<arr[front]<<endl;
        this->front = (this->front+1)%MAX;
        return 0;
    }
    int show()
    {
        if(pankong())
            throw -3;
        cout<<"从队头到队尾的元素为:";
        for(int i=this->front; i!=tail; i=(i+1)%MAX)
        {
            cout<<arr[i]<<"  ";
        }
        cout<<endl;
        return 0;
    }
};
int main()
{
    duilie<int> s1;
    cout<<s1.pankong()<<endl;
    cout<<s1.panman()<<endl;
    for(int i=1; i<8; i++)
    {
        try {
            s1.rudui(i);
        } catch (int n)
        {
            if(-1 == n)
                cout<<"队列已满,入队失败"<<endl;
        }
    }
    s1.show();
    s1.chudui();
    s1.show();
    cout<<s1.pankong()<<endl;
    cout<<s1.panman()<<endl;

    return 0;
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值