算法導論——隊列

頭文件queue.h如下:

#pragma once
#ifndef _QUEUE_H
#define _QUEUE_H
#define SIZE 100
class my_queue
{
private:
	using pos = char;
	typedef size_t poa;
public:
	void initqueue(my_queue &q);
	bool queueempty(my_queue &q);
	int enterqueue(my_queue &q, const pos &c);
	int deletequeue(my_queue &q, pos &c);
	int gethead(my_queue &q, pos &c) const;
	void clearqueue(my_queue &q);
	pos queue[SIZE] = { 0 };
	poa head=0;
	poa tail=0;
};

inline void my_queue::initqueue(my_queue &q)  //
{
	this->head = 0;
	this->tail = 0;
}

bool my_queue::queueempty(my_queue &q)
{
	if (this->head == this->tail)
		return 1;
	else
		return 0;
}

int my_queue::enterqueue(my_queue &q, const pos &c)
{
	if (this->tail >= SIZE-1)
		return 0;
	else
		this->queue[this->tail++] = c;
	return 1;
}

int my_queue::deletequeue(my_queue &q, pos &c)
{
	if (this->head==this->tail)
		return 0;
	else
		c = this->queue[this->head++];
	return 1;
}

int my_queue::gethead(my_queue &q, pos &c) const
{
	if (this->head <= 0)
		return 0;
	else
		c = this->queue[this->head];
	return 1;
}

void my_queue::clearqueue(my_queue &q)
{
	this->head = 0;
	this->tail = 0;
}
#endif

main函數如下:

#include<iostream>
#include"queue.h"

using namespace std;


int main()
{
	my_queue q1;
	int length = 8;
	char temp=0;
	char str[] = "abcdefgh";
	q1.initqueue(q1);
	for (size_t i = 0; i < length; ++i)
		q1.enterqueue(q1, str[i]);
	q1.deletequeue(q1, temp);
	cout << "出隊列的元素是:" << temp << endl;
	cout << "隊列中的元素是:" << "   ";
	if (q1.queueempty(q1))
		return -1;
	else
	{
		for (size_t i = q1.head; i < q1.tail; ++i)
			cout << q1.queue[i] << "   ";
		cout << endl;
	}
	return 0;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章