【C++】顺序队列

函数声明:

#include <iostream>
#include <assert.h>

#define SIZE 10
#define TRUE 1
#define FALSE 0

using namespace std;

class Queue
{
private:
	int* _data;
	int _size;
	int _head;
	int _tail;
//判空函数声明
	int IsEmpty_Queue();
//判满函数声明
	int IsFull_Queue();
public:
//构造函数
	Queue()
	{
		cout << "构造函数" << endl;

		_data = new int[SIZE];//注意:防止浅拷贝
		assert(_data != NULL);

		_head = 0;
		_tail = 0;
		_size = SIZE;
	}
//拷贝构造函数
	Queue(const Queue& queue)
	{
		cout << "拷贝构造函数" << endl;

		_data = new int[queue._size];//注意:防止浅拷贝
		assert(_data != NULL);

		for(int i = queue._head; i != queue._tail; i = (i+1)%queue._size)
		{
			_data[i] = queue._data[i];
		}

		_head = queue._head;
		_tail = queue._tail;
		_size = queue._size;
	}
//等号运算符重载函数
	Queue& operator = (const Queue& queue)
	{
		cout << "等号运算符重载函数" << endl;

		if(this == &queue)//注意:防止自己给自己赋值
		{
			return *this;
		}

		if(_data != NULL)//注意:防止内存泄漏
		{
			delete []_data;
		}

		_data = new int[queue._size];
		assert(_data != NULL);

		for(int i = queue._head; i != queue._tail; i = (i+1)%queue._size)
		{
			_data[i] = queue._data[i];
		}

		_head = queue._head;
		_tail = queue._tail;
		_size = queue._size;
	}
//析构函数
	~Queue()
	{
		cout << "析构函数" << endl;
		if(_data != NULL)
		{
			delete []_data;
			_data = NULL;
		}
		_head = 0;
		_tail = 0;
		_size = 0;
	}
//打印函数声明
	void Show_Queue();
//扩容函数声明
	void Expand_queue();
//出队函数声明
	int Pop_queue(int *res);
//入队函数声明
	void Push_queue(int val);
};

函数实现:

#include "Queue.h"

//判空函数
int Queue::IsEmpty_Queue()
{
	if(_tail == _head)
	{
		return TRUE;
	}
	return FALSE;
}
//判满函数
int Queue::IsFull_Queue()
{
	if((_tail + 1)%_size == _head)
	{
		return TRUE;
	}
	return FALSE;
}
//打印函数
void Queue::Show_Queue()
{
	for(int i = _head; i != _tail; i = (i+1)%_size)
	{
		cout << _data[i] << "  ";
	}
	cout << endl;
}
//扩容函数
void Queue::Expand_queue()
{
	_size *= 2;
	int* new_data = new int[_size];
	assert(new_data != NULL);

	for(int i = _head; i != _tail; i = (i + 1)%_size)
	{
		new_data[i] = _data[i];
	}

	delete []_data;
	_data = new_data;
}
//出队函数
int Queue::Pop_queue(int *res)
{
	if(IsEmpty_Queue())
	{
		return FALSE;
	}

	*res = _data[_head++];
	_head %= _size;

	return TRUE;
}
//入队函数
void Queue::Push_queue(int val)
{
	if(IsFull_Queue())
	{
		Expand_queue();
	}

	_data[_tail++] = val;
	_tail %= _size;
}

代码测试:

#include "Queue.h"

int main()
{
	Queue queue;

	for(int i = 0; i < 2; i++)
	{
		queue.Push_queue(i); 
	}

	queue.Show_Queue();

	int res = 0;
	for(int i = 0; i < 3; i++)
	{
		if(queue.Pop_queue(&res))
		{
			cout << "res = "<< res << endl;
		}
		else
		{
			cout <<"error!"<<endl;
		}
	}
	
	queue.Show_Queue();


	return 0;
}

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值