c++實現靜態循環隊列的各種操作

隊空時條件: front=rear
隊滿時條件: (rear+1)%maxsize=front

front指向隊首元素,rear指向隊尾元素的下一個元素。



代碼如下:

/*
本例用數組來模擬靜態循環隊列
隊列爲空的條件:隊列中一個元素也沒有,即front=rear,但此時front和rear不一定等於0
隊列爲滿的條件:假設創建了一個有6個元素的動態數組,則規定數組中有5個元素即爲滿
*/

#include <iostream>
using namespace std;

typedef struct Queue
{
    int *pBase;   //用來創建動態數組,指向動態數組的第一個元素
    int front;    //隊列中隊首元素的下標
    int rear;     //隊列中隊尾元素的下標加1,rear不是指向最後一個元素,而是最後元素後面的一個
}QUEUE;

void InitQueue(QUEUE *pQ);  //初始化一個隊列
bool IsEmpty(QUEUE *pQ); //判斷隊列是否爲空
bool IsFull(QUEUE *pQ);  //判斷隊列是否滿
void EnQueue(QUEUE *pQ, int value);  //入隊
void DeQueue(QUEUE *pQ); //出隊
void TraverseQueue(QUEUE *pQ);

int main()
{
    QUEUE Q;
    InitQueue(&Q);
    EnQueue(&Q, 1);
    EnQueue(&Q, 2);
    EnQueue(&Q, 3);
    EnQueue(&Q, 4);
    EnQueue(&Q, 5);
    EnQueue(&Q, 6);
    EnQueue(&Q, 7);
    EnQueue(&Q, 8);
    cout << "隊列中元素爲: ";
    TraverseQueue(&Q);
    cout << endl;
    DeQueue(&Q);
    DeQueue(&Q);
    DeQueue(&Q);
    cout << "隊列中剩餘元素爲:";
    TraverseQueue(&Q);
}

void InitQueue(QUEUE *pQ)
{
    pQ->pBase = new int[6];
    pQ->front = 0;
    pQ->rear = 0;
}

bool IsEmpty(QUEUE *pQ)
{
    if(pQ->front == pQ->rear)
        return true;
    else
        return false;
}

bool IsFull(QUEUE *pQ)
{
    if((pQ->rear+1)%6 == pQ->front)
        return true;
    else
        return false;
}

void EnQueue(QUEUE *pQ, int value)
{
    if(!IsFull(pQ))
    {
        pQ->pBase[pQ->rear] = value;
        pQ->rear = (pQ->rear+1) % 6;
    }
    else
        cout << "隊列已滿,不能插入數據" << value << endl;
}

void DeQueue(QUEUE *pQ)
{
    if(IsEmpty(pQ))
        cout << "隊列爲空,沒有數據出隊." << endl;
    else
    {
        cout << "出隊數據爲" << pQ->pBase[pQ->front] << endl;
        pQ->front = (pQ->front + 1) % 6;
    }
}

void TraverseQueue(QUEUE *pQ)
{
    int i = pQ->front;
    while(i != pQ->rear)
    {
        cout << pQ->pBase[i];
        i = (i+1) %6;
    }
}
運行結果:




發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章