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

การลบข้อมูลใน Queue (Dequeue) ด้วยภาษา C

Queue: โครงสร้างข้อมูลแบบ FIFO (First In First Out)

Insert ที่ Rear, Delete ที่ Front ใช้ Array ขนาดคงที่ MAX

เงื่อนไข

  • Queue Overflow: Rear == MAX-1 (เต็ม)
  • Queue Underflow: Front == -1 หรือ Front > Rear (ว่าง)

อัลกอริทึม

Insert: ถ้าไม่เต็ม Front=-1→0, Rear++, array[Rear]=item
Delete: ถ้าไม่ว่าง item=array[Front], Front++
Display: วนพิมพ์ array[Front] ถึง array[Rear]

โค้ด C สมบูรณ์

#include <stdio.h>
#define MAX 50

void insert();
int array[MAX];
int rear = -1;
int front = -1;

main() {
    int choice;
    while (1) {
        printf("1.Insert element to queue \n");
        printf("2.Delete an element from queue\n");
        printf("3.Display elements of queue \n");
        printf("4.Quit \n");
        printf("Enter your choice : ");
        scanf("%d", &choice);
        switch (choice) {
            case 1: insert(); break;
            case 2: delete(); break;
            case 3: display(); break;
            case 4: exit(1);
            default: printf("Wrong choice \n");
        }
    }
}

void insert() {
    int add_item;
    if (rear == MAX - 1)
        printf("Queue Overflow \n");
    else {
        if (front == -1) front = 0;
        printf("Inset the element in queue : ");
        scanf("%d", &add_item);
        rear = rear + 1;
        array[rear] = add_item;
    }
}

void display() {
    int i;
    if (front == -1)
        printf("Queue is empty \n");
    else {
        printf("Queue is : \n");
        for (i = front; i <= rear; i++)
            printf("%d ", array[i]);
        printf("\n");
    }
}

void delete() {
    if (front == -1 || front > rear) {
        printf("Queue Underflow \n");
        return;
    } else {
        printf("Element deleted from queue is : %d\n", array[front]);
        front = front + 1;
    }
}

ตัวอย่าง Output

1.Insert element to queue
2.Delete an element from queue
3.Display elements of queue
4.Quit
Enter your choice: 1
Inset the element in queue: 12
... (insert 23, 34)
Enter your choice: 2
Element deleted from queue is: 12
Queue is: 23 34
Enter your choice: 2
Element deleted from queue is: 23
Queue is: 34