C++笔试题之用数组实现队列

时间:2022-11-19 07:57:20


#ifndef QHPACKETQUEUE_H
#define QHPACKETQUEUE_H

#define MAX_QUEUE_SIZE 512

template<typename T>
class QHPacketQueue
{
public:
QHPacketQueue(int size=MAX_QUEUE_SIZE);
~QHPacketQueue();
public:
bool push(T data);
bool pop(T *data);
bool front(T *data);
bool back(T *data);
bool isFull();
bool isEmpty();
int count();
int size();
void clean();

private:
int m_size;
int m_head;
int m_tail;
int m_itemsCount;
T* m_data;
};

template<typename T>
QHPacketQueue<T>::QHPacketQueue(int size)
: m_size(size)
, m_head(0)
, m_tail(0)
, m_itemsCount(0)
, m_data(nullptr)
{
m_data = new T[m_size];
}

template<typename T>
QHPacketQueue<T>::~QHPacketQueue()
{
if (m_data)
{
delete[]m_data;
}
}

template<typename T>
bool QHPacketQueue<T>::push(T data)
{
if ((m_itemsCount >= m_size) || (nullptr == m_data))
{
return false;
}

int pos = (m_tail % m_size);
m_data[pos] = data;
m_tail++;
m_itemsCount++;

return true;
}

template<typename T>
bool QHPacketQueue<T>::pop(T *data)
{
if ((m_itemsCount == 0) || (nullptr == m_data))
{
return false;
}

int pos = (m_head % m_size);
*data = m_data[pos];
m_head++;
m_itemsCount--;

return true;
}

template<typename T>
bool QHPacketQueue<T>::front(T *data)
{
if ((m_itemsCount == 0) || (nullptr == m_data))
{
return false;
}

int pos = (m_head % m_size);
*data = m_data[pos];

return true;
}

template<typename T>
bool QHPacketQueue<T>::back(T *data)
{
if ((m_itemsCount == 0) || (nullptr == m_data))
{
return false;
}

int pos = (m_tail-1) % m_size;
*data = m_data[pos];

return true;
}

template<typename T>
bool QHPacketQueue<T>::isFull()
{
return (m_itemsCount >= m_size);
}

template<typename T>
bool QHPacketQueue<T>::isEmpty()
{
return (0 == m_itemsCount);
}

template<typename T>
int QHPacketQueue<T>::count()
{
return m_itemsCount;
}

template<typename T>
int QHPacketQueue<T>::size()
{
return m_size;
}

template<typename T>
void QHPacketQueue<T>::clean()
{
m_head = 0;
m_tail = 0;
m_itemsCount = 0;
}

#endif // QHPACKETQUEUE_H