1. 程式人生 > >資料結構之環形佇列實現(1)

資料結構之環形佇列實現(1)

注意:判空,判佇列滿,
MyQueue.h

#ifndef MYQUEUE_H
#define MYQUEUE_H
/*
    環形佇列C++實現
*/
class MyQueue{
public:
    MyQueue(int queueCapacity);     //建構函式
    virtual ~MyQueue();
    void ClearQueue();
    bool QueueEmpty() const;
    bool QueueFull() const;
    int QueueLength() const;
    bool EnQueue(int element);
    bool
DeQueue(int &element); void QueueTraverse(); private: int *m_pQueue; int m_iQueueLen; int m_iQueueCapacity; int m_iHead; int m_iTail; }; #endif

MyQueue.cpp

#include "MyQueue.h"
#include<iostream>
using namespace std;

MyQueue::MyQueue(int queueCapacity){
    m_iQueueCapacity = queueCapacity;
    m_pQueue = new
int[m_iQueueCapacity];//有可能申請失敗 ClearQueue(); } MyQueue::~MyQueue(){ delete[]m_pQueue; m_pQueue = nullptr; } void MyQueue::ClearQueue(){ m_iHead = 0; m_iTail = 0; m_iQueueLen = 0; } bool MyQueue::QueueEmpty() const{ return m_iQueueLen == 0 ? true : false; } int MyQueue::QueueLength() const
{ return m_iQueueLen; } bool MyQueue::QueueFull() const{ if (m_iQueueLen == m_iQueueCapacity) return true; return false; } bool MyQueue::EnQueue(int element){ if (QueueFull()) return false; m_pQueue[m_iTail] = element; m_iTail++; m_iQueueLen++; m_iTail %= m_iQueueCapacity; return true; } bool MyQueue::DeQueue(int &element){ if (QueueEmpty()) return false; element = m_pQueue[m_iHead]; m_iHead++; m_iQueueLen--; m_iHead %= m_iQueueCapacity; return true; } void MyQueue::QueueTraverse(){ cout << endl; for (int i = m_iHead; i < m_iQueueLen + m_iHead; i++){ cout << m_pQueue[i%m_iQueueCapacity] << endl; } cout << endl; }

Test.cpp

#include<iostream>
#include "MyQueue.h"
using namespace std;

int main(){
    MyQueue *p = new MyQueue(4);
    p->EnQueue(10);
    p->EnQueue(12);
    p->EnQueue(16);
    p->EnQueue(18);
    p->QueueTraverse();

    int e = 0;
    p->DeQueue(e);
    cout << endl;
    cout << e << endl;

    p->DeQueue(e);
    cout << endl;
    cout << e << endl;

    cout << endl;
    p->QueueTraverse();

    p->ClearQueue();
    p->QueueTraverse();

    p->EnQueue(20);
    p->EnQueue(30);
    p->QueueTraverse();

    delete p;
    p = NULL;
    return 0;
}