[C++] 数据结构之顺序队列

不知道有没有错误。

///
// Queue.h : CQueue 顺序队列类 
// 

#include <assert.h>
#define QUEUE_SIZE 100

template <class Type>
class CQueue {
// 方法
public :
	// 构造
	CQueue();
	CQueue(Type arrInitial[], int iLen);
	
	// 是否为空
	bool IsEmpty();
	// 取队头元素
	Type GetTop();
	// 取队长度
	int GetSize();  
	
	// 入队(返回队长度)
	int Push(Type value);
	// 出队(返回队长度)
	int Pop(); 
	
	// 清空队列 
	void Clear();
	 
// 属性
private :
	 Type m_arrQueue[QUEUE_SIZE];
	 int m_pHead, m_pTail;
	 
	 // 是否已满
	 bool m_bFull; 
};

// 构造
template <class Type>
CQueue<Type>::CQueue()
{
	m_pHead = m_pTail = 0;
}

// 构造
template <class Type>
CQueue<Type>::CQueue(Type arrInitial[], int iLen)
{
	m_pHead = 0;
	m_pTail = iLen;
	assert(iLen <= QUEUE_SIZE);
	
	for(int i = 1; i <= iLen; i++)
		m_arrQueue[i - 1] = arrInitial[i - 1];
}

// 是否为空
template <class Type>
bool CQueue<Type>::IsEmpty()
{
	return (m_pHead == m_pTail && !m_bFull);	
}

// 入队(返回队长度)
template <class Type>
int CQueue<Type>::Push(Type value)
{
	assert(m_pTail != m_pHead || !m_bFull);
	
	m_pTail++;
	m_pTail %= QUEUE_SIZE;
	
	if (m_pTail == m_pHead && !m_bFull)
		m_bFull = true;
	
	m_arrQueue[m_pTail - 1] = value;
	return GetSize();
}

// 出队(返回队长度)
template <class Type>
int CQueue<Type>::Pop()
{
	assert(m_pTail != m_pHead || m_bFull);
	
	m_pHead++;
	m_pHead %= QUEUE_SIZE;
	
	if (m_pTail != m_pHead && m_bFull)
		m_bFull = false;
		
	return GetSize();
} 

// 取队长度
template <class Type>
int CQueue<Type>::GetSize()
{
	if (m_pTail >= m_pHead && !m_bFull) 
		return m_pTail - m_pHead;
	if (m_pTail < m_pHead && !m_bFull)
		return QUEUE_SIZE - m_pHead + m_pTail;
	if (m_bFull)
		return QUEUE_SIZE;
}

// 取队头元素 
template <class Type>
Type CQueue<Type>::GetTop()
{
	assert(!IsEmpty());
	return m_arrQueue[m_pHead];
}

// 清空队列
template <class Type>
void CQueue<Type>::Clear()
{
	m_pHead = m_pTail = 0;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值