码迷,mamicode.com
首页 > 其他好文 > 详细

3.3.2 循环队列

时间:2020-03-31 10:45:00      阅读:73      评论:0      收藏:0      [点我收藏+]

标签:exit   maxsize   als   put   clu   code   enqueue   cpp   max   

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 循环队列

标签:exit   maxsize   als   put   clu   code   enqueue   cpp   max   

原文地址:https://www.cnblogs.com/SlowIsFast/p/12603368.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!