Circular Queue เชื่อมตำแหน่งสุดท้ายกับแรกเป็นวงกลม ใช้ Array ขนาดคงที่
ตัวอย่างโค้ดสมบูรณ์
#include <iostream>
using namespace std;
const int MAX = 5;
int cqueue[MAX];
int front = -1, rear = -1;
void insertCQ(int val) {
if ((front == 0 && rear == MAX-1) || (front == rear + 1)) {
cout << "Queue Overflow\n";
return;
}
if (front == -1) {
front = rear = 0;
} else if (rear == MAX - 1) {
rear = 0;
} else {
rear++;
}
cqueue[rear] = val;
}
void deleteCQ() {
if (front == -1) {
cout << "Queue Underflow\n";
return;
}
cout << "Element deleted: " << cqueue[front] << endl;
if (front == rear) {
front = rear = -1;
} else if (front == MAX - 1) {
front = 0;
} else {
front++;
}
}
void displayCQ() {
if (front == -1) {
cout << "Queue is empty\n";
return;
}
cout << "Queue elements: ";
int f = front, r = rear;
if (f <= r) {
while (f <= r) cout << cqueue[f++] << " ";
} else {
while (f <= MAX-1) cout << cqueue[f++] << " ";
f = 0;
while (f <= r) cout << cqueue[f++] << " ";
}
cout << endl;
}
int main() {
int ch, val;
do {
cout << "1)Insert 2)Delete 3)Display 4)Exit\nEnter choice: ";
cin >> ch;
switch (ch) {
case 1: cout << "Input: "; cin >> val; insertCQ(val); break;
case 2: deleteCQ(); break;
case 3: displayCQ(); break;
case 4: cout << "Exit\n"; break;
default: cout << "Incorrect!\n";
}
} while (ch != 4);
return 0;
}
การทำงานหลัก
- Insert: ตรวจ Overflow → Update Rear (Wrap around) → Store
- Delete: ตรวจ Underflow → Read Front → Update Front (Wrap around)
- Display: จัดการ 2 กรณี: Front ≤ Rear (Linear) หรือ Front > Rear (Wrapped)
C++ STL Alternative
ไม่มี Circular Queue โดยตรงใน STL แต่ใช้ std::deque หรือ Boost Circular Buffer ได้