본문 바로가기
자료구조

[C++/자료구조] 큐(Queue)

by MY블로그 2023. 7. 8.

Queue : 큐

- 특징

1) 선입선출(FIFO) 구조를 가지는 자료구조
2) 삽입은 enqueue, 삭제는 dequeue 연산을 사용

- 장점

1) 구현이 간단하다
2) 작업 처리 대기열, 메세지 전달 등에서 유용하다

- 단점

1) 큐의 크기가 고정되어 있을 때, 큐가 가득 차면 더 이상 데이터를 추가할 수 없다

큐(Queue)는 먼저입력된 값이 먼저 빠져나가는 선입선출 (First In First Out / FIFO) 구조 이다.

Queue.h
#pragma once

void DoQueue();

class Queue
{
public:
	Queue();

	bool Empty();
	bool Full();

	int GetSize();

	void Enqueue(DataType data);
	void Dequeue();

	DataType GetFront();

private:
	int Front;
	int Rear;
	int Size;
	DataType Data[MAX_SIZE];
};
Queue.cpp
#include "../../stdafx.h"
#include "Queue.h"

void DoQueue()
{
	Queue q;
	q.Enqueue(23);
	q.Enqueue(5242);
	q.Enqueue(151);

	cout << "Queue Size	  : " << q.GetSize() << endl;

	cout << "Front element  : " << q.GetFront() << endl;
	q.Dequeue();

	cout << "Front element  : " << q.GetFront() << endl;
	q.Dequeue();

	cout << "Front element  : " << q.GetFront() << endl;
	q.Dequeue();

	cout << "Front element  : " << q.GetFront() << endl;
	q.Dequeue();

	cout << "Queue Size	  : " << q.GetSize() << endl;

	Pause;
	return;
}

Queue::Queue()
	: Front(0), Rear(0), Size(0) {}

bool Queue::Empty()
{
	return Size == 0;
}

bool Queue::Full()
{
	return Size == MAX_SIZE;
}

int Queue::GetSize()
{
	return Size;
}

void Queue::Enqueue(DataType data)
{
	if (Full())
	{
		cout << "Queue is Full" << endl;
		return;
	}

	Data[Rear] = data;
	Rear = (Rear + 1) % MAX_SIZE;
	Size++;
}

void Queue::Dequeue()
{
	if (Empty())
	{
		cout << "Queue is Empty" << endl;
		return;
	}

	Front = (Front + 1) % MAX_SIZE;
	Size--;
}

DataType Queue::GetFront()
{
	if (Empty())
	{
		cout << "Queue is Empty" << endl;
		return DataType();
	}

	return Data[Front];
}

댓글