-
Notifications
You must be signed in to change notification settings - Fork 44
Expand file tree
/
Copy pathQueue.java
More file actions
53 lines (46 loc) · 1.23 KB
/
Queue.java
File metadata and controls
53 lines (46 loc) · 1.23 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
class Queue {
private int[] arr;
private int front, rear, size, capacity;
public Queue(int capacity) {
this.capacity = capacity;
arr = new int[capacity];
front = 0;
rear = -1;
size = 0;
}
public void enqueue(int data) {
if (size == capacity) throw new RuntimeException("Queue is full");
rear = (rear + 1) % capacity;
arr[rear] = data;
size++;
}
public int dequeue() {
if (size == 0) throw new RuntimeException("Queue is empty");
int val = arr[front];
front = (front + 1) % capacity;
size--;
return val;
}
public int peek() {
if (size == 0) throw new RuntimeException("Queue is empty");
return arr[front];
}
public boolean isEmpty() {
return size == 0;
}
public boolean isFull() {
return size == capacity;
}
public static void main(String[] args) {
Queue q = new Queue(5);
q.enqueue(10);
q.enqueue(20);
q.enqueue(30);
System.out.println(q.dequeue());
System.out.println(q.peek());
q.enqueue(40);
q.enqueue(50);
q.enqueue(60);
System.out.println(q.isFull());
}
}