8.30作业

自己实现queue(队列) 和 stack(栈)

stack:

#include <iostream>
#include<vector>


using namespace std;

template<typename T>
class mystack
{
private:
    vector<T> v;
public:
    mystack(){}
    mystack(const mystack& c)
    {
        this->v=c.v;
    }
    ~mystack(){}

    bool empty()
    {
        return  this->v.empty();
    }

    bool full()
    {
        return this->v.full();
    }

    void push(int e)
    {
        this->v.push_back(e);
    }

    T top()
    {
        if(this->empty())
        {
            cout<<"empty"<<endl;
            return -1;
        }
        return  this->v.back();
    }

    void pop()
    {
        if(this->empty())
        {
            cout<<"empty"<<endl;
        }
      this->v.pop_back();
    }
    size_t size()
    {
        return  this->v.size();
    }

};
int main()
{
    mystack<int> m;
    cout<<m.empty()<<endl;
    m.pop();
    for(int i=1;i<=10;i++)
    {
        m.push(i);
        cout<<m.top()<<" ";
    }
    return 0;
}

queue:

#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()
{

    myqueue<int> m1;
    cout<<m1.empty()<<endl;
    for(int i=1;i<=20;i++)
    {
        m1.push(i);
        cout<<m1.size()<<endl;
    }
    
}


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值