C++_Day03手动封装一个循环顺序队列类

手动封装一个循环顺序队列类
私有成员属性:存放队列的数组、两个变量分别记录队头和队尾下标
公有成员函数: 入队(push( type value ))
出队(pop())
展示(show)
求队列长度(size()):要求时间复杂度在常量级别
判满( bool full())
判空(bool empty())

#include<iostream>
using namespace std;
#define ERR_MSG(MSG) do{ \
    cout<<"line:"<<__LINE__<<":"<<MSG; \
    }while(0);

#define MAX_SIZE 7  //MAX_SIZE-1是队列最多能存放的数据个数
class queue_cir
{
public:
    void push(int value);
    void pop(void);
    void show(void);
    int size(void);
    bool full(void);
    bool empty(void);
private:
    int queue[MAX_SIZE] = {0};
    int head = 0, rear = 0;
};

//入队
void queue_cir::push(int value)
{
    cout<<"push():"<<endl;
    if (full())
    {
        ERR_MSG("push:队列已满,不可入队\n");
        return ;
    }
    queue[rear] = value;
    rear = (rear+1)%MAX_SIZE;    
}

//出队
void queue_cir::pop(void)
{
    cout<<"pop():"<<endl;
    if (empty())
    {
        ERR_MSG("pop:队列已空,不可出队\n");
        return ;
    }
    cout<<queue[head]<<" was popped"<<endl;
    head = (head+1)%MAX_SIZE;
}

//遍历输出
void queue_cir::show(void)
{
    cout<<"data remaining:";
    if (empty())
    {
        ERR_MSG("show:队列为空\n");
        return ;
    }
    int head_n = head;
    while((head_n) != rear)
    {
        cout<<queue[head_n]<<" ";
        head_n = (head_n+1)%MAX_SIZE;

    }
    cout<<endl;
}

//输出队列大小
int queue_cir::size(void)
{
    //如果head大于read,需要将rear加上MAX_SIZE再减去head
    return (head<rear) ? rear-head : rear+MAX_SIZE-head;
}

//队列判满
bool queue_cir::full(void)
{
    //队列满的状态是队尾+1等于队头
    return (rear+1)%MAX_SIZE == head ? true : false;
}

//队列判空
bool queue_cir::empty(void)
{
    //队列空的状态是队尾等于队头
    return rear == head ? true : false;
}

int main(int argc, char const *argv[])
{
    queue_cir q1;
    //push测试
    cout<< (q1.empty() ? "queue empty":"queue full")<<endl;
    q1.pop();
    int j = 30;
    for(int i = 0; i<7; i++)
    {
        cout<<q1.size()<<" data remaining"<<endl;
        q1.push(j--);
        q1.show();
    }
    //pop测试
    cout<< (q1.full() ? "queue full":"queue empty")<<endl;
    for(int i = 0; i<7; i++)
    {
        q1.pop();
        q1.show();
    }

    return 0;
}

在这里插入图片描述

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值