Repository navigation
Expand file tree
/
Copy pathDequeueByArray.java
More file actions
95 lines (73 loc) · 2.03 KB
/
Copy pathDequeueByArray.java
File metadata and controls
95 lines (73 loc) · 2.03 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
package com.hellokoding.datastructure;
import java.util.NoSuchElementException;
public class DequeueByArray {
private int[] dequeue;
private int front;
private int rear;
public DequeueByArray(int capacity) {
this.dequeue = new int[capacity];
this.front = 0;
this.rear = 0;
}
public void enqueueFirst(int x) {
if (isFull()) {
throw new IllegalStateException();
}
for (int i = rear; i > front ; i--) {
dequeue[i] = dequeue[i-1];
}
dequeue[front] = x;
rear++;
}
public void enqueueLast(int x) {
if (isFull()) {
throw new IllegalStateException();
}
dequeue[rear++] = x;
}
public int dequeueFirst() {
if (isEmpty()) {
throw new NoSuchElementException();
}
return dequeue[front++];
}
public int dequeueLast() {
if (isEmpty()) {
throw new NoSuchElementException();
}
return dequeue[rear--];
}
public int front() {
if (isEmpty()) {
throw new NoSuchElementException();
}
return dequeue[front];
}
public int rear() {
if (isEmpty()) {
throw new NoSuchElementException();
}
return dequeue[rear-1];
}
public boolean isEmpty() {
return front == rear;
}
public boolean isFull() {
return rear == dequeue.length;
}
public int size() {
return rear - front;
}
public static void main(String[] args) {
DequeueByArray myQueue = new DequeueByArray(3);
myQueue.enqueueFirst(1);
myQueue.enqueueLast(2);
myQueue.enqueueFirst(3);
System.out.println(myQueue.front()); // 3
System.out.println(myQueue.dequeueFirst()); // 3
System.out.println(myQueue.front()); // 1
System.out.println(myQueue.size()); // 2
System.out.println(myQueue.isEmpty()); // false
System.out.println(myQueue.isFull()); // false
}
}