3.3.2 循环队列

Posted slowisfast

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了3.3.2 循环队列相关的知识,希望对你有一定的参考价值。

Queue.h

#pragma once
#include<iostream>
using namespace std;

class Queue {
public:
    int front;
    int rear;
    int maxSize;
    int* elements;

    Queue(int size=20){
        maxSize = size;
        elements = new int[maxSize];
        front = 0;
        rear = 0;
    }
    bool IsFull() {
        return (rear + 1) % maxSize == front;
    }
    bool IsEmpty() {
        return rear == front;
    }
    bool EnQueue(int elem) {
        bool res = true;
        if (IsFull() == true) {
            res = false;
        }
        else {
            elements[rear] = elem;
            rear = (rear + 1) % maxSize;
        }
        return res;
    }
    bool DeQueue(int& x) {
        bool res = true;
        if (IsEmpty() == true) {
            res = false;
        }
        else {
            x = elements[front];
            front = (front + 1) % maxSize;
        }
        return res;
    }
};

main.cpp

#include"Queue.h"

int main() {
    Queue q;
    int i = 0;
    int temp;
    bool bl;
    while (q.EnQueue(i)) {
        i++;
    }
    cout << "Output 5 elements & input 5 elements!" << endl;
    cout << "There are the 5 elements output:" << endl;
    for (int index = 0; index < 5; index++) {
        if (q.DeQueue(temp)) {
            cout << temp << " ";
            q.EnQueue(i++);
        }
        else {
            cerr << "OutputError!!!" << endl;
            exit(1);
        }
    }
    cout << endl;
    cout << "The left-over elements output:" << endl;
    while (q.DeQueue(temp)) {
        cout << temp << " ";
    }
    cout << endl;
    return 0;
}

 

以上是关于3.3.2 循环队列的主要内容,如果未能解决你的问题,请参考以下文章

# Java 常用代码片段

# Java 常用代码片段

常用python日期日志获取内容循环的代码片段

使用从循环内的代码片段中提取的函数避免代码冗余/计算开销

代码适用于与单个 html 文件不同的堆栈片段

AVKit – 视频片段仅循环 2 次