Queue Insert Operation (Enqueue) แบบ Array
เน้นเฉพาะการ Insert และ Display ไม่มี Delete
โค้ด 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.Display elements of queue \n");
printf("3.Quit \n");
printf("Enter your choice : ");
scanf("%d", &choice);
switch (choice) {
case 1: insert(); break;
case 2: display(); break;
case 3: 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");
}
}
ตัวอย่าง Output
1.Insert element to queue
2.Display elements of queue
3.Quit
Enter your choice: 1
Inset the element in queue: 34
Enter your choice: 1
Inset the element in queue: 24
Enter your choice: 2
Queue is: 34 24
Enter your choice: 3