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

Posted 草上爬

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了C++笔试题之用数组实现队列相关的知识,希望对你有一定的参考价值。

#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

原文链接:C++面试题/笔试题之用数组实现队列_草上爬的博客-CSDN博客

以上是关于C++笔试题之用数组实现队列的主要内容,如果未能解决你的问题,请参考以下文章

[04数据结构]栈和队列的基本理解操作和笔试题

笔试题102-117

经典笔试题:线程通信(使用重入锁(ReentrantLock)和条件队列(Condition)实现线程间通信)

今日头条笔试题--2018 优先队列

笔试题大集合

Java之用栈实现队列