2023/5/9 C++实现循环队列

手动封装一个循环顺序队列类(Queue)

私有成员属性:存放队列的数组、两个变量分别记录队头和队尾下标

公有成员函数: 入队(push( type value ))

                        出队(pop())

                        展示(show)

                        求队列长度(size()):要求时间复杂度在常量级别

                        判满( bool full())

                        判空(bool empty())

//head
#ifndef HEAD_H
#define HEAD_H
#include <iostream>
#define MAXSIZE 5

using namespace std;


typedef int datatype;
class Queue
{
private:
    int front;
    int rear;
    datatype data[MAXSIZE];
public:
    //构造函数初始化头尾指针
    Queue()
    {
        front = rear = 0;
    }
    //入队
    void push(datatype val);
    //出队
    void pop();
    //展示
    void show();
    //队列长度
    int size();
    //判满
    bool full();
    //判空
    bool empty();
};
#endif // HEAD_H
//function
#include"head.h"

//入队
void Queue::push(datatype val)
{
    if(full())
    {
        cout << "队列已满" << endl;
        return;
    }
    data[rear] = val;
    rear = (rear + 1) % MAXSIZE; //队尾指针向后移动
}
//出队
void Queue::pop()
{
    if(empty())
    {
        cout << "队列为空" << endl;
        return;
    }
    cout << "出队元素:"<< data[front] << endl;
    front = (front+1)%MAXSIZE;
}
//展示
void Queue::show()
{
    if(empty())
    {
        cout<<"队列为空"<<endl;
        return;
    }
    //遍历
    for(int i=front; i!=rear; i=(i+1)%MAXSIZE)
    {
        cout<<data[i]<<" "<<endl;
    }
}
//队列长度
int Queue::size()
{
    return (rear - front + MAXSIZE) % MAXSIZE;
}
//判满
bool Queue::full()
{
    if(front == (rear + 1)%MAXSIZE)
    {
        return true;
    }
    return false;
}
//判空
bool Queue::empty()
{
    if(rear == front)
    {
        return true;
    }
    return false;
}
#include "head.h"

int main()
{
    Queue queue;
    //入队操作
    queue.push(1);
    queue.push(2);
    queue.push(3);
    queue.push(4);
    queue.push(5);
    queue.push(2);


    cout <<"队列长度:" << queue.size() << endl;
    //遍历
    queue.show();
    //出队列
    queue.pop();
    //遍历
    queue.show();

    cout <<"队列长度:" << queue.size() << endl;
    return 0;
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值