빙수달 게임 개발 노트

[알고리즘] 큐(Queue) 본문

Programming/알고리즘

[알고리즘] 큐(Queue)

빙수달 2025. 7. 8. 17:20
#include <iostream>
#include <cstdlib>
using namespace std;

// Queue의 기본 용량 정의
#define SIZE 1000

// Queue를 저장할 클래스
class Queue
{
	int* arr;
	int capacity;
	int front;
	int rear;
	int count;

public:
	Queue(int size = SIZE);		// 생성자
	~Queue();

	int dequeue();		
	void enqueue(int x);
	int peek();
	int size();
	bool isEmpty();
	bool isFull();
};

// Queue를 초기화하는 생성자
Queue::Queue(int size)
{
	arr = new int[size];
	capacity = size;
	front = 0;
	rear = -1;
	count = 0;
}

// Queue에 할당된 메모리를 해제하는 소멸자
Queue::~Queue()
{
	delete[] arr;
}

int Queue::dequeue()
{
	if (isEmpty())
	{
		cout << "Underflow\nProgram Terminated\n";
		exit(EXIT_FAILURE);
	}

	int x = arr[front];
	cout << "Removing " << x << endl;

	front = (front + 1) % capacity;
	count--;

	return x;
}

void Queue::enqueue(int item)
{
	if(isFull())
	{
		cout << "Overflow\nProgram Terminated\n";
		exit(EXIT_FAILURE);
	}

	cout << "Insereting " << item << endl;

	rear = (rear + 1) % capacity;
	arr[rear] = item;
	count++;
}

int Queue::peek()
{
	if (isEmpty())
	{
		cout << "Underflow\nProgrm Terminated\n";
		exit(EXIT_FAILURE);
	}
	return arr[front];
}

int Queue::size()
{
	return count;
}

bool Queue::isEmpty()
{
	return(size() == 0);
}

bool Queue::isFull()
{
	return (size() == capacity);
}

int main()
{
	Queue q(5);
	string command;

	cout << "=== Queue 프로그램 시작 ===\n";
	cout << "명령어 입력: push, pop, peek, size, exit\n";

	while (true)
	{
		cout << "\n> ";
		cin >> command;

		if(command == "push")
		{
			int value;
			cin >> value;
			q.enqueue(value);
		}
		else if(command == "pop")
		{
			q.dequeue();
		}
		else if (command == "peek")
		{
			cout << "Front 요소: " << q.peek() << endl;
		}
		else if (command == "size")
		{
			cout << "현재 큐 크기: " << q.size() << endl;
		}
		else if (command == "exit")
		{
			cout << "프로그램을 종료합니다.\n";
			break;
		}
		else
		{
			cout << "잘못된 명령어입니다. 다시 입력하세요.\n";
		}
	}

	return 0;
}