Queue(1)Queue的顺序实现之循环队列版本

queue.h


/*----------------------------------------------- 
Created By EverSteins 
Email:EverSteins@gmail.com
转载请注明出处
------------------------------------------------*/ 

#ifndef QUEUE_H
#define QUEUE_H
#include "utility.h"

typedef int ElemType ;

//循环队列,核心思想是插入时留一个空格,避免插入和弹出时无法判断空还是满的状态
//这样能减少一个表示元素大小的空间
class Queue
{
public:
	Queue():rear_(0),front_(0){}

	bool Empty() const
	{
		return rear_ == front_ ;
	}

	bool Full() const
	{
		return (rear_ + 1) % kMaxQueueSize == front_;    //插入时留一个空间
	}

	size_t Size() const
	{
		return (rear_ - front_ + kMaxQueueSize) % kMaxQueueSize;   //这个实现技巧要注意
	}

	bool Top(ElemType &item) const;

	bool Push(const ElemType &item);
	bool Pop();

private:
	static const size_t kMaxQueueSize = 5;

	size_t rear_;      //即将插入的位置,还没有元素占用
	size_t front_;     //即将弹出的位置,有元素占用

	ElemType entry_[kMaxQueueSize];
};

#endif

queue.cpp


/*----------------------------------------------- 
Created By EverSteins 
Email:EverSteins@gmail.com
转载请注明出处
------------------------------------------------*/ 

#include "stdafx.h"
#include "utility.h"
#include "queue.h"

bool Queue::Top(ElemType &item) const
{
	if (Empty())
		return false;

	item = entry_[front_];
	return true;
}

bool Queue::Push(const ElemType &item)
{
	if (Full())
		return false;

	
	entry_[rear_] = item;
	rear_ = (rear_ + 1) % kMaxQueueSize;

	return true;
}

bool Queue::Pop()
{
	if (Empty())
		return false;

	front_ = (front_ + 1) % kMaxQueueSize;

	return true;
}

utility.h

/*----------------------------------------------- 
Created By EverSteins 
Email:EverSteins@gmail.com
转载请注明出处
------------------------------------------------*/ 

#ifndef UTILITY_H
#define UTILITY_H
#include <cstddef>
#include <cstdlib>

#define DISALLOW_COPY_AND_ASSIGN(TypeName) \
  TypeName(const TypeName&);               \
  void operator=(const TypeName&)

#endif

main.cpp

/*----------------------------------------------- 
Created By EverSteins 
Email:EverSteins@gmail.com
转载请注明出处
------------------------------------------------*/
#include "stdafx.h"
#include "queue.h"
#include <iostream>
using namespace std;

int _tmain(int argc, _TCHAR* argv[])
{
	Queue q1;
	q1.Push(1);
	q1.Push(2);
	q1.Push(3);
	q1.Push(4);
	q1.Push(5);
	q1.Pop();
	q1.Push(6);
	q1.Push(7);

	cout<<q1.Size()<<endl;
	while (!q1.Empty())     //猜猜最后结果是多少
	{
		int tmp;
		q1.Top(tmp);
		cout<<tmp<<' ';
		q1.Pop();
	}

	cout<<endl;

	cin.get();


	return 0;
}








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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值