-
Notifications
You must be signed in to change notification settings - Fork 0
/
MyQueue.java
46 lines (37 loc) · 867 Bytes
/
MyQueue.java
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
public class MyQueue {
int capacity;
int front;
int rear;
int size;
int[] queue;
MyQueue(int capacity) {
this.capacity = capacity;
size = 0;
front = 0;
rear = 0;
queue = new int[capacity];
}
public void offer(int data) {
if (size >= capacity) {
throw new OverflowQueueException();
}
queue[rear++] = data;
size++;
if (rear == capacity) {
rear = 0;
}
}
public int poll() {
if (size <= 0) {
throw new EmptyQueueException();
}
size--;
int num = queue[front++];
if (front == capacity) {
front = 0;
}
return num;
}
}
class EmptyQueueException extends RuntimeException {}
class OverflowQueueException extends RuntimeException {}