Repository navigation
Expand file tree
/
Copy pathQueue.java
More file actions
98 lines (82 loc) · 2.61 KB
/
Copy pathQueue.java
File metadata and controls
98 lines (82 loc) · 2.61 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
97
98
class Queue {
private int arr[]; // Array to store queue elements
private int front; // Front points to the front element in the queue
private int rear; // Rear points to the last element in the queue
private int capacity; // Maximum capacity of the queue
private int count; // Current size of the queue
// Constructor to initialize the queue
Queue(int size) {
arr = new int[size];
capacity = size;
front = 0;
rear = -1;
count = 0;
}
// Utility function to add an item to the queue
public void enqueue(int item) {
// Check for queue overflow
if (isFull()) {
System.out.println("Queue Overflow");
System.exit(1);
}
System.out.println("Inserting " + item);
rear = (rear + 1) % capacity;
arr[rear] = item;
count++;
}
// Utility function to remove front element from the queue
public int dequeue() {
// Check for queue underflow
if (isEmpty()) {
System.out.println("Queue Underflow");
System.exit(1);
}
int item = arr[front];
System.out.println("Removing " + item);
front = (front + 1) % capacity;
count--;
return item;
}
// Utility function to return the front element of the queue
public int peek() {
if (isEmpty()) {
System.out.println("Queue Underflow");
System.exit(1);
}
return arr[front];
}
// Utility function to return the size of the queue
public int size() {
return count;
}
// Utility function to check if the queue is empty
public boolean isEmpty() {
return (size() == 0);
}
// Utility function to check if the queue is full
public boolean isFull() {
return (size() == capacity);
}
// Display elements of the queue
public void printQueue() {
if (isEmpty()) {
System.out.println("Queue is empty");
return;
}
for (int i = 0; i < count; i++) {
System.out.print(arr[(front + i) % capacity] + " ");
}
System.out.println();
}
public static void main(String[] args) {
Queue queue = new Queue(5);
queue.enqueue(1);
queue.enqueue(2);
queue.enqueue(3);
System.out.print("Queue: ");
queue.printQueue();
queue.dequeue();
System.out.println("After dequeue");
queue.printQueue();
}
}