环形队列 C++

本文介绍了使用C++编写的队列类CQueue,包含QueuePush方法用于入队,QueuePop方法用于出队,以及QueueGetFirstIdx方法获取队首元素索引。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

/*main.c*/

#include "stdio.h"
#include "Queue.h"
#include <iostream>
using namespace std;
int num = 0;
int main()
{
  CQueue Test1;
  static int number = 0;

  while(1)
  switch (num)
  {
  case 1:
	number++;
	Test1.QueuePush(number);
	cout << "\nHead is " << Test1.QueueGetFirstIdx() << endl;
	num = 0;
	break;
  case 2:
	Test1.QueuePop();
	cout << "\nHead is " << Test1.QueueGetFirstIdx() << endl;
	num = 0;
	break;
  case 3:
	cout << "\nHead is " << Test1.QueueGetFirstIdx() << endl;
	break;
  default:
	break;
  }
  
  
}
/*Queue.cpp*/
#include "Queue.h"

bool CQueue::QueuePush(long date)
{
  unsigned short tmp;
  tmp = (tail + 1) & (QUEUE_ELEM_NUM - 1);
  if (tmp == head)
	return false;
  tail = tmp;
  Data[tmp] = date;
  num++;
  return true;
}
//------------------------------------------------------------------------------
bool CQueue::QueuePop()
{
  if (tail == head)
	return false;

  head = (head + 1) & (QUEUE_ELEM_NUM - 1);
  Data[head] = 0;
  num--;
  return true;
}
//------------------------------------------------------------------------------
unsigned short CQueue::QueueGetFirstIdx()
{
  return ((head + 1) & (QUEUE_ELEM_NUM - 1));
}


/*Queue.h*/
#ifndef  __QUEUE_H__
#define  __QUEUE_H__
#ifdef __cplusplus
extern "C" {
#endif



#define	QUEUE_ELEM_NUM		(4)			//队列元素数量

class CQueue
{

  public:
	bool QueuePush(long date);
	bool QueuePop();
	unsigned short QueueGetFirstIdx();
  private:
	int 	Data[QUEUE_ELEM_NUM] = { 0 };
	unsigned short	head = 0;
	unsigned short	tail = 0;
	unsigned short	num = 0;

};






#ifdef __cplusplus
}
#endif

#endif  //__QUEUE_H__

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值