# 循环队列的实现

xiaoxiao2021-02-28  11

Queue.h

#pragma once #ifndef QUEUE_H #define QUEUE_H class Queue { public: Queue(int MaxSize=10000); ~Queue(); bool empty() const; bool full() const; int size() const; int first() const; int last() const; int pop(); Queue* push(int data); void output() const; private: int front; int rear; int MaxSize; int *Element; }; #endif

Queue.cpp

#include "Queue.h" #include<stdio.h> Queue::Queue(int MaxSize) { front = 0; rear = 0; this->MaxSize = MaxSize; Element = new int[MaxSize+1]; } Queue::~Queue() { delete[] Element; } bool Queue::empty() const { return front == rear; } bool Queue::full() const { return (rear + 1) % (MaxSize + 1) == front; } int Queue::size() const { int i = 0; int _front_ = front; for (; _front_ != rear;) { i++; _front_ = (_front_ + 1) % (MaxSize + 1); } return i; } int Queue::first() const { if (empty()) { printf("queue is empty\n"); return -1; } return Element[front]; } int Queue::last() const { if (empty()) { printf("queue is empty\n"); return -1; } return Element[rear-1]; } int Queue::pop() { if (empty()) { printf("queue is empty\n"); return -1; } else { int output = Element[front]; front = (front + 1) % (MaxSize + 1); return output; } } Queue* Queue::push(int data) { if (full()) { printf("queue is full\n"); } else { Element[rear] = data; rear = (rear + 1) % (MaxSize + 1); } return this; } void Queue::output() const { if (empty()) { printf("list is empty\n"); return; } for (int _index_ = front; _index_ != rear;) { printf("%d ", Element[_index_]); _index_ = (_index_ + 1) % (MaxSize + 1); } printf("\n"); }