1 StaticQueue实现
1.1 队列的顺序实现

1.2 StaticQueue设计要点
类模板
- 使用原生数组作为队列的存储空间。
- 使用模板参数决定队列的最大容量。

1.3 StaticQueue实现要点(循环计数法)
关键操作:
- 进队列:m_space[m_rear] = e; m_rear = (m_rear + 1) % N;
- 出队列:m_front = (m_front + 1) % N;
队列的状态:
- 对空:(m_length == 0) && (m_front == m_rear)
- 对满:(m_length == N) && (m_front == m_rear)
2 StaticQueue实现
StaticQueue.h
#ifndef STATICQUEUE_H
#define STATICQUEUE_H
#include "Queue.h"
#include "Exception.h"
namespace LemonLib
{
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()
{
m_length = 0;
m_front = 0;
m_rear = 0;
}
int capacity() const
{
return N;
}
void add(const T& e)
{
if (m_length < N)
{
m_space[m_rear] = e;
m_rear = (m_rear + 1) % N;
m_length++;
}
else
{
THROW_EXCEPTION(InvalidOperationException, "No space in current queue ...");
}
}
void remove()
{
if (m_length > 0)
{
m_front = (m_front + 1) % N;
m_length--;
}
else
{
THROW_EXCEPTION(InvalidOperationException, "No element in current queue ...");
}
}
T front() const
{
if (m_length > 0)
{
return m_space[m_front];
}
else
{
THROW_EXCEPTION(InvalidOperationException, "No element in current queue ...");
}
}
void clear()
{
m_length = 0;
m_front = 0;
m_rear = 0;
}
int length() const
{
return m_length;
}
~StaticQueue()
{
clear();
}
};
}
#endif // STATICQUEUE_H
3 小结
- 队列是一种特殊的线性表,具有先进先出的特性
- 队列只允许在线性表的两端进行操作,一端进,一端出
- StaticQueue使用原声数组作为内部存储空间
- StaticQueue的最大容量由模板参数决定
- StaticQueue采用循环计数法提高队列操作的效率
本文详细介绍了StaticQueue的实现原理,包括使用原生数组作为存储空间、模板参数决定最大容量等设计要点。通过循环计数法提高队列操作效率,探讨了队列状态判断的关键操作。
5003

被折叠的 条评论
为什么被折叠?



