DS - Simple Queue
A simple queue
is a fundamental data structure that follows the First-In, First-Out (FIFO)
principle. This means that the first element added to the queue will be the first one to be removed, just like people standing in line—whoever gets in first is served first.
Key Operations in a Simple Queue:
Enqueue (Insertion)
: Adding an element to the back of the queue.Dequeue (Removal)
: Removing an element from the front of the queue.Peek (Front)
: Viewing the element at the front of the queue without removing it.isEmpty
: Checking if the queue is empty.
Example: Think of a line at a movie theater. The first person in line buys the ticket first, and as more people arrive, they join at the back of the line. When a person buys a ticket and leaves, the next person in line gets their turn.
Visual Example:
Initial queue: [1, 2, 3] (1 is at the front, 3 is at the back)Enqueue(4): [1, 2, 3, 4]Dequeue(): [2, 3, 4] (1 is removed)
Applications:
Task scheduling
(e.g., in operating systems)Breadth-First Search (BFS)
in graph traversalManaging resources
in simulations
It’s a simple, efficient way to handle processes where order matters!
Program:
1#include <stdio.h>
2#include <stdlib.h>
3#define n 5
4int a[n];
5int f = -1;
6int r = -1;
7void enqueue(int e)
8{
9 if (r == n - 1)
10 {
11 printf("Q is full\n");
12 }
13 else
14 {
15 if (f == -1 && r == -1)
16 {
17 f = 0;
18 r = 0;
19 }
20 else
21 {
22 r++;
23 }
24 a[r] = e;
25 printf("inserted successfully\n");
26
27 }
28}
29
30void dequeue()
31{
32 if (f == -1 && r == -1)
33 {
34 printf("Q is empty\n");
35 }
36 else
37 {
38 if (f == r)
39 {
40 f = -1;
41 r = -1;
42 }
43 else
44 {
45 f++;
46 }
47 }
48}
49
50void display()
51{
52 if (f == -1 && r == -1)
53 {
54 printf("queue is empty\n");
55 }
56 else
57 {
58 printf("Queue:\n");
59 for (int i = f; i <= r; i++)
60 {
61 printf("%d\t", a[i]);
62 }
63 printf("\n");
64 }
65}
66
67int main()
68{
69 int ch, d, c;
70 while (1)
71 {
72 printf("1. enqueue operation\n");
73 printf("2. dequeue operation\n");
74 printf("3. Display queue\n");
75 printf("4. exit\n");
76 printf("enter your choice\n");
77 scanf("%d", &ch);
78 switch (ch)
79 {
80 case 1:
81 printf("enter the data\n");
82 scanf("%d", &d);
83 enqueue(d);
84 break;
85 case 2:
86 dequeue();
87 break;
88
89 case 3:
90 display();
91 break;
92
93 case 4:
94 exit(0);
95 break;
96
97 default:
98 printf("invalid operation\n");
99 }
100 }
101}