Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> C++

โปรแกรม C++ ใช้ Array สร้าง Queue (คิว)

Queue (คิว) แบบ Array ใช้ FIFO (First In, First Out) เก็บข้อมูลในอาร์เรย์ขนาดคงที่

โครงสร้างข้อมูล

const int MAX_SIZE = 100;
int queue[MAX_SIZE];
int front = -1, rear = -1;

โค้ดโปรแกรม Queue ด้วย Array

#include <iostream>
using namespace std;

const int MAX_SIZE = 100;
int queue[MAX_SIZE];
int front = -1, rear = -1;

void enqueue(int val) {
    if (rear == MAX_SIZE - 1) {
        cout << "Queue Overflow!" << endl;
        return;
    }
    
    if (front == -1)  // คิวว่าง ตัวแรก
        front = 0;
    
    rear++;
    queue[rear] = val;
    cout << val << " enqueued." << endl;
}

void dequeue() {
    if (front == -1 || front > rear) {
        cout << "Queue Underflow!" << endl;
        return;
    }
    
    cout << "Dequeued: " << queue[front] << endl;
    front++;
    
    // รีเซ็ตเมื่อคิวว่าง
    if (front > rear)
        front = rear = -1;
}

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

int main() {
    int choice, val;
    
    do {
        cout << "\n1. Enqueue\n2. Dequeue\n3. Display\n4. Exit\nChoice: ";
        cin >> choice;
        
        switch (choice) {
            case 1:
                cout << "Enter value: ";
                cin >> val;
                enqueue(val);
                break;
            case 2:
                dequeue();
                break;
            case 3:
                display();
                break;
            case 4:
                cout << "Exiting..." << endl;
                break;
            default:
                cout << "Invalid choice!" << endl;
        }
    } while (choice != 4);
    
    return 0;
}

ผลลัพธ์ตัวอย่าง

1. Enqueue
2. Dequeue
3. Display
4. Exit
Choice: 1
Enter value: 10
10 enqueued.
Choice: 1
Enter value: 20
20 enqueued.
Choice: 3
Queue: 10 20
Choice: 2
Dequeued: 10
Choice: 3
Queue: 20
Choice: 4
Exiting...

ข้อจำกัดของ Array Queue

ปัญหา คำอธิบาย
Fixed Sizeต้องกำหนด MAX_SIZE ล่วงหน้า ไม่ยืดหยุ่น
Overflowเพิ่มไม่ได้เมื่อ rear = MAX_SIZE-1
Memory Wasteพื้นที่หน้าคิวที่ถูกลบออกแล้ว ใช้ไม่ได้ (False Overflow)

แก้ไขด้วย Circular Queue

ใช้ modulo operator เพื่อให้ rear วิ่งวนกลับมา index 0:

rear = (rear + 1) % MAX_SIZE;
front = (front + 1) % MAX_SIZE;

Circular Queue ใช้พื้นที่อาร์เรย์ได้เต็มที่ ไม่มี False Overflow

เปรียบเทียบ Array vs Linked List Queue

คุณสมบัติ Array Queue Linked List Queue
ขนาดคงที่ (Fixed)ไดนามิก (Dynamic)
Memoryจองล่วงหน้าจองตามต้องการ
Speedเร็วกว่าเล็กน้อย (Cache friendly)ช้ากว่าเล็กน้อย (Pointer chasing)
Implementationง่ายกว่าซับซ้อนกว่า