-
Notifications
You must be signed in to change notification settings - Fork 0
/
MyQueue.java
70 lines (60 loc) · 1.4 KB
/
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
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
public class MyQueue<E> {
private Node<E> head;
private Node<E> tail;
private int size;
public MyQueue() {
this.size = 0;
}
private static class Node<E> {
E value;
Node<E> next;
public Node(E value) {
this.value = value;
this.next = null;
}
}
public int size() {
return size;
}
public void enqueue(E value) {
Node<E> newNode = new Node<E>(value);
if (head == null) {
head = newNode;
tail = newNode;
} else {
tail.next = newNode;
tail = tail.next;
}
size++;
}
public E peek() {
return head.value;
}
public E dequeue() {
if (size <= 0)
return null;
if (head.equals(tail)) {
tail = null;
}
E value = head.value;
head = head.next;
size--;
return value;
}
public String toString() {
if (size == 0)
return "[ ]";
Node<E> node = head;
StringBuilder sb = new StringBuilder();
for (int i = 0; i < size; i++) {
sb.append("[ ");
sb.append(node.value);
sb.append(" ]");
if (node.next != null) {
node = node.next;
sb.append(" --> ");
}
}
return sb.toString();
}
}