可以看完这篇博客再来看代码

循环队列的实现

#include <iostream>
using namespace std;

typedef int Elem;
struct Queue
{
    Elem *arr;
    int head;
    int tail;
    int length;
    int size_;
};
/*
*   @creat      初始化栈
*   @push       压栈
*   @pop        出栈
*   @destory     销毁栈
*/
void creat(Queue *que, int n);
void enQue(Queue *que, Elem data);
Elem getHead(Queue *que);
Elem deQue(Queue *que);
bool isFull(Queue *que);
bool isEmpty(Queue *que);
void destory(Queue *que);

void print(Queue *que)
{
    for(int i(0); i<que->size_; i++)
    {
        if(i < que->size_- 1)
            cout << que->arr[i] << ' ';
        else
            cout << que->arr[i] << endl;
    }
}
int main()
{
    Queue que;
    creat(&que, 5);
    int arr[6] = {1, 2, 3, 4, 5, 6};
    ///这里第六个是溢出的.
    for(int i(0); i<6; i++)
    {
        enQue(&que, arr[i]);
    }
    cout << "原队列:" << endl;
    print(&que);
    cout << "-----------------------(0代表没有元素)" << endl;
    cout << "出队:" << endl;
    deQue(&que);
    print(&que);

    cout << "99入队:" << endl;
    enQue(&que, 99);
    print(&que);

    return 0;
}

void creat(Queue *que, int size_)
{
    que->arr = new Elem[size_+1];
    que->head = 0;
    que->tail = 0;
    que->length = 0;
    que->size_ = size_ + 1;
}

void enQue(Queue *que, Elem data)
{
    if(!isFull(que))
    {
        que->arr[que->tail] = data;
        que->tail = (que->tail + 1) % que->size_;
        que->length++;
    }
    else
        cout << "The queue is full." << endl;
}

Elem deQue(Queue *que)
{
    if(!isEmpty(que))
    {
        que->length--;
        Elem data = que->arr[que->head];
        que->arr[que->head] = 0;
        que->head = (que->head + 1) % que->size_;
        return data;
    }
    return -1;
}

bool isFull(Queue *que)
{
    return (que->tail + 1) % que->size_ == que->head;
}
bool isEmpty(Queue *que)
{
    return que->head == que->tail;
}
void destory(Queue *que)
{
    que->length = 0;
    delete[] que->arr;
}

Elem getHead(Queue *que)
{
    return que->arr[que->head];
}

运行结果(看不懂无所谓了)