8.30日作业

作业内容

用C++封装栈容器库
用C++封装队列容器库

栈代码

在这里插入代码片#include <iostream>
#define LEN 100
using namespace std;
template <typename T>
class mystack
{
private:
    T date[LEN];
    int top;
public:
    //构造函数
    mystack()
    {
        top = -1;
    }
    //析构函数
    ~mystack(){}
    //拷贝赋值函数
    mystack& operator=(const mystack& other)
    {
        memcpy(this->data,other.date,LEN);
        this->top = other.top;
    }
    //栈顶元素访问
    T top_()
    {
        if(empty() == true)
        {
            cout<<"空栈"<<endl;
            throw -1;
        }
        cout<<this->date[top]<<endl;
        return this->date[top];
    }

    //判空
    bool empty()
    {
        return (top == -1);//判断栈顶是否有值,没有则栈空,返回failse
    }
    //判满
    bool full()
    {
        return (top == LEN-1);
    }
    //容纳的元素数
    int size()
    {
        return top+1;
    }
    //向栈顶插入元素
    void push(T e)
    {
        if(full() == true)
        {
            cout<<"栈已满"<<endl;
            return;
        }
        top++;
        this->date[top]=e;
    }
    //删除栈顶元素
    void pop()
    {
        if(empty() == true)
        {
            cout<<"空栈"<<endl;
            return;
        }
        top--;
    }
};
int main()
{
    mystack<int> v;
    v.push(1);
    v.top_();
    return 0;
}

队列代码

在这里插入代码片#include <iostream>
#define LEN 100
using namespace std;
template <typename T>
class myqueue
{
private:
    T date[LEN];
    int front;
    int back;
public:
    //构造函数
    myqueue()
    {
        this->date = front;
        back=front;
    }
    //析构函数
    ~myqueue(){}
    //拷贝赋值函数
    myqueue& operator=(const myqueue& other)
    {
        memcpy(this->data,other.date,LEN);
        this->front = other.front;
        this->back = other.back;
    }
    //访问第一个元素
    T v_front()
    {
        if(empty() == true)
        {
            cout<<"空队列"<<endl;
            throw -1;
        }
        return this->date[front];
    }

    //访问最后一个元素
    T v_back()
    {
        if(empty() == true)
        {
            cout<<"空队列"<<endl;
            throw -1;
        }
        return this->date[back-1];
    }
    //判空
    bool empty()
    {
        return (back == front);//队尾是否等于队头
    }
    //判满
    bool full()
    {
        return (back == LEN);
    }
    //容纳的元素数
    int size()
    {
        return back+1;
    }
    //向队尾插入元素
    void push(T e)
    {
        if(full() == true)
        {
            cout<<"队列已满"<<endl;
            return;
        }
        back++;
        this->date[back]=e;
    }
    //删除队头元素
    void pop()
    {
        if(empty() == true)
        {
            cout<<"空队列"<<endl;
            return;
        }
        front--;
    }
};
int main()
{

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值