使用C++的类实现循环顺序队列

1、作业要求

        使用C++的类实现循环顺序队列。

2、实现过程

1)queue.h文件

#ifndef QUEUE_H
#define QUEUE_H

#define MAX 10

class Queue {
private:
    int* data;
    int front;
    int tail;

public:
    //初始化
    void init();

    //判空
    bool queue_empty();

    //入队
    void queue_push(int e);

    //遍历
    void queue_show();

    //出队
    void queue_pop();

    //队列长度
    int queue_size();

    //销毁
    void queue_delete();
};

#endif // QUEUE_H

2)queue.cpp文件

#include <iostream>
#include <queue.h>

using namespace std;

//初始化
void Queue::init() {
    data = new int[MAX];
    front = 0;
    tail = 0;

}

//判空
bool Queue::queue_empty() {
    return front==tail;
}

//入队
void Queue::queue_push(int e) {
    data[tail] = e;
    cout << data[tail] << " 入队成功" << endl;
    tail = (tail+1)%MAX;

}

//遍历
void Queue::queue_show() {
    if(queue_empty()) {
        cout << "遍历失败" << endl;
    }

    for(int i=front; i!=tail; i=(i+1)%MAX) {
        cout <<  data[i] << "  ";
    }
    cout << endl;
}

//出队
void Queue::queue_pop() {
    if(queue_empty()) {
        cout << "出队失败" << endl;
    }
    cout << data[front] << " 出队成功" << endl;
    front = (front+1) % MAX;
}

//队列长度
int Queue::queue_size() {
    if(queue_empty()) {
        cout << "长度为0" << endl;
    }

    return (tail+MAX-front)%MAX;
}

//销毁
void Queue::queue_delete() {
    delete []data;
    data = nullptr;
    cout << "销毁成功" << endl;
}

3)main.cpp文件

#include <iostream>
#include <queue.h>

using namespace std;

int main()
{
    Queue q1;
    //初始化
    q1.init();

    //入队
    q1.queue_push(5);
    q1.queue_push(9);
    q1.queue_push(7);
    q1.queue_push(6);
    q1.queue_push(2);

    //遍历
    q1.queue_show();

    //出队
    q1.queue_pop();
    q1.queue_pop();
    q1.queue_pop();
    //遍历
    q1.queue_show();

    //队列长度
    cout << "队列长度为:" << q1.queue_size() << endl;

    //销毁
    q1.queue_delete();

    return 0;
}

3、效果截图

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值