-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathQueue.java
More file actions
69 lines (60 loc) · 1.38 KB
/
Queue.java
File metadata and controls
69 lines (60 loc) · 1.38 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
class QNode<T> {
T data;
QNode<T> next;
public QNode(T d) {
data = d;
next = null;
}
}
public class Queue<T> {
private QNode<T> front, rear;
public Queue() {
front = rear = null;
}
public Queue(Queue<T> other) {
front = rear = null;
if (other == null || other.isEmpty())
return;
QNode<T> current = other.front;
while (current != null) {
add(current.data);
current = current.next;
}
}
public void add(T x) {
QNode<T> n = new QNode<>(x);
if (rear == null) {
rear = front = n;
} else {
rear.next = n;
rear = n;
}
}
public T poll() {
if (front != null) {
T value = front.data;
front = front.next;
if (front == null) {
rear = null;
}
return value;
}
return null;
}
public boolean isEmpty() {
return front == null;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder("[");
QNode<T> temp = front;
while (temp != null) {
sb.append(temp.data);
if (temp.next != null)
sb.append(", ");
temp = temp.next;
}
sb.append("]");
return sb.toString();
}
}