-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCircularQueue.java
More file actions
96 lines (89 loc) · 2.75 KB
/
CircularQueue.java
File metadata and controls
96 lines (89 loc) · 2.75 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
import java.util.Scanner;
public class CircularQueue {
private static int front, rear, capacity;
private static int queue[];
CircularQueue(int size) {
front = rear = -1;
capacity = size;
queue = new int[capacity];
}
static void enqueue(int item) {
if ((rear + 1) % capacity == front) {
System.out.println("\nQueue is full\n");
return;
} else {
if (front == -1) {
front = 0;
}
rear = (rear + 1) % capacity;
queue[rear] = item;
System.out.println(item + " successfully inserted in the queue");
}
}
static void dequeue() {
if (front == -1) {
System.out.println("Queue Empty");
return;
} else if (front == rear) {
System.out.println(queue[front] + " dequeued successfully");
front = -1;
rear = -1;
} else {
System.out.println(queue[front] + " dequeued successfully");
front = (front + 1) % capacity;
}
}
static void display() {
if (front == -1) {
System.out.println("\nQueue is empty\n");
return;
} else {
for (int i = front; ; i = (i + 1) % capacity) {
System.out.print(queue[i] + " ");
if (i == rear) {
break;
}
}
System.out.println();
}
}
static void QueueFront() {
if (front == -1) {
System.out.println("\nQueue is empty\n");
} else {
System.out.println("Front element of the queue is: " + queue[front]);
}
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter the size of the queue: ");
int n = sc.nextInt();
new CircularQueue(n);
for (;;) {
System.out.println("\nMenu:\n1.Enqueue \n2.Dequeue \n3.Display \n4.Front element\n5.Exit");
int choice = sc.nextInt();
switch (choice) {
case 1:
System.out.println("Enter the element to be inserted: ");
int ele = sc.nextInt();
enqueue(ele);
break;
case 2:
dequeue();
break;
case 3:
display();
break;
case 4:
QueueFront();
break;
case 5:
sc.close();
return;
default:
System.out.println("Invalid choice");
break;
}
}
}
}