-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMyQueue.java
More file actions
78 lines (65 loc) · 1.13 KB
/
Copy pathMyQueue.java
File metadata and controls
78 lines (65 loc) · 1.13 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
package queue;
import java.util.ArrayList;
import java.util.NoSuchElementException;
public class MyQueue<T> {
ArrayList<T> arr = new ArrayList<T>();
int size = 0;
public MyQueue() {
}
public int size() {
return size;
}
public boolean isEmpty() {
if (size == 0) {
return true;
}
return false;
}
public void add(T element) {
arr.add(element);
size++;
}
public T remove() {
T element = arr.get(0);
if (isEmpty()) {
throw new NoSuchElementException();
}
arr.remove(0);
size--;
return element;
}
public T poll() {
if (isEmpty()) {
return null;
}
T element = arr.get(0);
arr.remove(0);
size--;
return element;
}
public T peek() {
if (isEmpty()) {
return null;
}
return arr.get(0);
}
public T element() {
if (isEmpty()) {
throw new NoSuchElementException();
}
return arr.get(0);
}
public String toString() {
if (isEmpty()) {
return null;
}
StringBuilder str = new StringBuilder("[");
for (int i = 0; i < size - 1; i++) {
str.append(arr.get(i));
str.append(", ");
}
str.append(arr.get(size - 1));
str.append("]");
return str.toString();
}
}