Computer >> 컴퓨터 >  >> 프로그래밍 >> C++

배열로 큐(Queue) 구현하기: C++ 프로그램 완벽 가이드

큐(Queue)란 무엇인가?

큐(Queue)는 여러 개의 요소를 담는 추상 자료구조입니다. 큐는 FIFO(First In First Out, 선입선출) 방식을 따르며, 이는 가장 먼저 삽입된 요소가 가장 먼저 삭제된다는 뜻입니다. 다시 말해, 큐에서는 가장 오래전에 추가된 요소가 우선적으로 제거됩니다.

아래는 배열을 사용하여 큐를 구현한 C++ 프로그램입니다.

예제 코드

#include <iostream>
using namespace std;
int queue[100], n = 100, front = - 1, rear = - 1;
void Insert() {
   int val;
   if (rear == n - 1)
   cout<<"Queue Overflow"<<endl;
   else {
      if (front == - 1)
      front = 0;
      cout<<"Insert the element in queue : "<<endl;
      cin>>val;
      rear++;
      queue[rear] = val;
   }
}
void Delete() {
   if (front == - 1 || front > rear) {
      cout<<"Queue Underflow ";
      return ;
   } else {
      cout<<"Element deleted from queue is : "<< queue[front] <<endl;
      front++;
   }
}
void Display() {
   if (front == - 1)
   cout<<"Queue is empty"<<endl;
   else {
      cout<<"Queue elements are : ";
      for (int i = front; i <= rear; i++)
      cout<<queue[i]<<" ";
         cout<<endl;
   }
}
int main() {
   int ch;
   cout<<"1) Insert element to queue"<<endl;
   cout<<"2) Delete element from queue"<<endl;
   cout<<"3) Display all the elements of queue"<<endl;
   cout<<"4) Exit"<<endl;
   do {
      cout<<"Enter your choice : "<<endl;
      cin>>ch;
      switch (ch) {
         case 1: Insert();
         break;
         case 2: Delete();
         break;
         case 3: Display();
         break;
         case 4: cout<<"Exit"<<endl;
         break;
         default: cout<<"Invalid choice"<<endl;
      }
   } while(ch!=4);
   return 0;
}

실행 결과

1) Insert element to queue
2) Delete element from queue
3) Display all the elements of queue
4) Exit
Enter your choice : 1
Insert the element in queue : 4
Enter your choice : 1
Insert the element in queue : 3
Enter your choice : 1
Insert the element in queue : 5
Enter your choice : 2
Element deleted from queue is : 4
Enter your choice : 3
Queue elements are : 3 5
Enter your choice : 7
Invalid choice
Enter your choice : 4
Exit

코드 상세 설명

1. Insert() 함수 – 요소 삽입

Insert() 함수는 큐에 새로운 요소를 삽입하는 역할을 합니다. rear 값이 n-1과 같다면 큐가 가득 찬 상태이므로 "Queue Overflow"(오버플로우) 메시지를 출력합니다. 만약 front가 -1이라면 큐가 비어 있는 상태이므로 front를 0으로 설정한 뒤, rear를 1 증가시키고 해당 인덱스 위치에 입력받은 요소를 저장합니다.

void Insert() {
   int val;
   if (rear == n - 1)
   cout<<"Queue Overflow"<<endl;
   else {
      if (front == - 1)
      front = 0;
      cout<<"Insert the element in queue : "<<endl;
      cin>>val;
      rear++;
      queue[rear] = val;
   }
}

2. Delete() 함수 – 요소 삭제

Delete() 함수는 큐에서 요소를 삭제합니다. 큐에 요소가 하나도 없다면(front가 -1이거나 front가 rear보다 큰 경우) 언더플로우(Underflow) 상태로 간주하여 메시지를 출력하고 함수를 종료합니다. 그렇지 않은 경우에는 front 위치에 있는 요소를 화면에 출력한 후 front 값을 1 증가시켜 다음 요소를 가리키도록 합니다.

void Delete() {
   if (front == - 1 || front > rear) {
      cout<<"Queue Underflow ";
      return ;
   }
   else {
      cout<<"Element deleted from queue is : "<< queue[front] <<endl;
      front++;
   }
}

3. Display() 함수 – 전체 요소 출력

Display() 함수는 큐에 저장된 모든 요소를 출력합니다. front가 -1이면 큐가 비어 있다는 메시지를 표시하고, 그렇지 않으면 for 반복문을 이용해 front부터 rear까지의 모든 요소를 순서대로 화면에 나타냅니다.

void Display() {
   if (front == - 1)
   cout<<"Queue is empty"<<endl;
   else {
      cout<<"Queue elements are : ";
      for (int i = front; i <= rear; i++)
      cout<<queue[i]<<" ";
      cout<<endl;
   }
}

4. main() 함수 – 메뉴 선택 처리

main() 함수는 사용자에게 메뉴를 제공하여 요소 삽입, 삭제, 전체 출력 중 원하는 작업을 직접 선택할 수 있도록 합니다. 사용자의 입력값에 따라 switch 문이 적절한 함수를 호출하며, 존재하지 않는 메뉴 번호를 입력하면 "Invalid choice"라는 안내 메시지를 출력합니다. 사용자가 4번(Exit)을 선택할 때까지 do-while 반복문이 프로그램을 계속 유지합니다.

int main() {
   int ch;
   cout<<"1) Insert element to queue"<<endl;
   cout<<"2) Delete element from queue"<<endl;
   cout<<"3) Display all the elements of queue"<<endl;
   cout<<"4) Exit"<<endl;
   do {
      cout<<"Enter your choice : "<<endl;
      cin>>ch;
      switch (ch) {
         case 1: Insert();
         break;
         case 2: Delete();
         break;
         case 3: Display();
         break;
         case 4: cout<<"Exit"<<endl;
         break;
         default: cout<<"Invalid choice"<<endl;
      }
   } while(ch!=4);
   return 0;
}

마무리

이 프로그램은 배열 기반 큐의 핵심 동작 원리인 삽입(enqueue), 삭제(dequeue), 출력 과정을 명확하게 보여줍니다. 다만 단순 배열 큐는 삭제된 앞쪽 공간을 재활용하지 못하는 한계가 있습니다. 실무에서는 이를 보완한 원형 큐(Circular Queue)를 구현하거나, C++ STL에서 제공하는 std::queue 컨테이너를 활용하는 것이 더 효율적입니다.