36_队列的概念及实现(上)

2018-07-13  本文已影响30人  编程半岛

关键词:队列的定义、队列的特性、队列的操作、队列的继承、StaticQueue

0. 队列的定义

1. 队列的特性

先进先出(First In First Out)

队列的特征示意图

2. 队列的操作

3. 队列的继承

队列的继承关系图
Queue.h
#ifndef QUEUE_H
#define QUEUE_H

#include "Object.h"

namespace DTLib
{

template < typename T >
class Queue : public Object
{
public:
    virtual void add(const T& e) = 0;
    virtual void remove() = 0;
    virtual T front() const = 0;
    virtual void clear() = 0;
    virtual int length() const = 0;
};

}

#endif // QUEUE_H

4. 队列的顺序实现

StaticQueue示意图

StaticQueue.h

#ifndef STATICQUEUE_H
#define STATICQUEUE_H

#include "Queue.h"
#include "Exception.h"

namespace DTLib
{

template < typename T, int N >
class StaticQueue : public Queue<T>
{
protected:
    T m_space[N];
    int m_front;
    int m_rear;
    int m_length;
public:
    StaticQueue();
    void add(const T& e);
    void remove();
    T front() const;
    void clear();
    int length() const;
    int capacity() const;
};

template <typename T, int N >
StaticQueue<T, N>::StaticQueue()
{
    m_rear = 0;
    m_front = 0;
    m_length = 0;
}

template <typename T, int N >
void StaticQueue<T, N>::add(const T& e)
{
    if( m_length < N )
    {
        m_space[m_rear] = e;
        m_rear = ( m_rear + 1 ) % N;
        ++m_length;
    }
    else
    {
        THROW_EXCEPTION(InvalidOperationExcetion, "Not space add queue...");
    }
}

template <typename T, int N >
void StaticQueue<T, N>::remove()
{
    if( m_length > 0 )
    {
        m_front = (m_front + 1) % N;
        --m_length;
    }
    else
    {
        THROW_EXCEPTION(InvalidOperationExcetion, "Not element remove queue...");
    }
}

template <typename T, int N >
T StaticQueue<T, N>::front() const
{
    if( m_length > 0 )
    {
        return m_space[m_front];
    }
    else
    {
        THROW_EXCEPTION(InvalidOperationExcetion, "Not element remove queue...");
    }
}

template <typename T, int N >
void StaticQueue<T, N>::clear()
{
    m_rear = 0;
    m_front = 0;
    m_length = 0;
}

template <typename T, int N >
int StaticQueue<T, N>::length() const
{
    return m_length;
}

template <typename T, int N >
int StaticQueue<T, N>::capacity() const
{
    return N;
}


}

#endif // STATICQUEUE_H

5. 小结

声明:此文章仅是本人在学习狄泰学院《数据结构实战开发教程》所做的笔记,文章中包含狄泰软件资料内容,一切版权归狄泰软件所有!
实验环境:ubuntu10 + Qt Creator2.4.1 + Qt SDK 4.7.4

上一篇 下一篇

猜你喜欢

热点阅读