-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathArray Queue
More file actions
92 lines (79 loc) · 2.48 KB
/
Array Queue
File metadata and controls
92 lines (79 loc) · 2.48 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
public class ArrayQueue {
private int[] queue;
private int front, rear, size, capacity;
// Constructor to initialize the queue
public ArrayQueue(int capacity) {
this.capacity = capacity;
this.queue = new int[capacity];
this.front = 0;
this.rear = -1;
this.size = 0;
}
// Method to add an element to the queue
public void enqueue(int item) {
if (isFull()) {
System.out.println("Queue is full!");
return;
}
rear = (rear + 1) % capacity;
queue[rear] = item;
size++;
}
// Method to remove an element from the queue
public int dequeue() {
if (isEmpty()) {
System.out.println("Queue is empty!");
return -1; // Return a sentinel value
}
int item = queue[front];
front = (front + 1) % capacity;
size--;
return item;
}
// Method to get the front element of the queue
public int peek() {
if (isEmpty()) {
System.out.println("Queue is empty!");
return -1; // Return a sentinel value
}
return queue[front];
}
// Method to check if the queue is empty
public boolean isEmpty() {
return size == 0;
}
// Method to check if the queue is full
public boolean isFull() {
return size == capacity;
}
// Method to get the size of the queue
public int getSize() {
return size;
}
// Method to display the elements of the queue
public void display() {
if (isEmpty()) {
System.out.println("Queue is empty!");
return;
}
System.out.print("Queue elements: ");
for (int i = 0; i < size; i++) {
System.out.print(queue[(front + i) % capacity] + " ");
}
System.out.println();
}
public static void main(String[] args) {
ArrayQueue queue = new ArrayQueue(5); // Create a queue with capacity 5
queue.enqueue(10);
queue.enqueue(20);
queue.enqueue(30);
queue.enqueue(40);
queue.enqueue(50);
queue.display(); // Output: Queue elements: 10 20 30 40 50
System.out.println("Dequeue: " + queue.dequeue()); // Output: Dequeue: 10
System.out.println("Peek: " + queue.peek()); // Output: Peek: 20
queue.display(); // Output: Queue elements: 20 30 40 50
queue.enqueue(60);
queue.display(); // Output: Queue elements: 20 30 40 50 60
}
}