-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathQueueBasic.java
More file actions
82 lines (73 loc) · 2.44 KB
/
QueueBasic.java
File metadata and controls
82 lines (73 loc) · 2.44 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
// Program: Queue Implementation Using Arrays
// Topic: Queue Data Structure
// Description: Implements a linear queue using an integer array with basic operations — `enqueue()`, `dequeue()`, and `peek()`.
// Demonstrates queue behavior (FIFO – First In, First Out) using circular indexing with modulo arithmetic to optimize space.
// Includes boundary checks to prevent overflow and underflow, and provides a simple test in the `main()` method.
package queue;
/**
*
* @author Samim
*/
public class QueueBasic {
private int maxSize;
private int[] queueArray;
private int front;
private int rear;
private int size;
public QueueBasic(int maxSize) {
this.maxSize = maxSize;
this.queueArray = new int[maxSize];
this.front = 0;
this.size = 0;
}
public void enqueue(int data) {
if (!isFull()) {
rear = (rear + 1) % maxSize;
queueArray[rear] = data;
size++;
} else {
System.out.println("Queue is full. Cannot enqueue " + data);
}
}
public int dequeue() {
if (!isEmpty()) {
int data = queueArray[front];
front = (front + 1) % maxSize;
//System.out.println(front);
size--;
return data;
} else {
System.out.println("Queue is empty. Cannot dequeue.");
return -1;
}
}
public int peek() {
if (!isEmpty()) {
return queueArray[front];
} else {
System.out.println("Queue is empty. Cannot peek.");
return -1;
}
}
public boolean isEmpty() {
return size == 0;
}
public boolean isFull() {
return size == maxSize;
}
public static void main(String[] args) {
QueueBasic queue = new QueueBasic(5);
queue.enqueue(10);
queue.enqueue(20);
queue.enqueue(30);
System.out.println("Peek: " + queue.peek());
//System.out.println("Dequeue: " + queue.dequeue());
System.out.println("Dequeue: " + queue.dequeue());
System.out.println("Peek: " + queue.peek());
queue.enqueue(40);
queue.enqueue(50);
System.out.println("Dequeue: " + queue.dequeue());
queue.enqueue(60); // This will cause overflow
System.out.println("Peek: " + queue.peek());
}
}