Skip to content

Commit fce3d83

Browse files
update LinkedQueue
1 parent c63dbad commit fce3d83

File tree

1 file changed

+17
-2
lines changed

1 file changed

+17
-2
lines changed

DataStructures/Queues/LinkedQueue.java

Lines changed: 17 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -80,6 +80,11 @@ public int dequeue() {
8080
front.next = front.next.next;
8181
destroy = null; /* clear let GC do it's work */
8282
size--;
83+
84+
if (isEmpty()) {
85+
front = rear;
86+
}
87+
8388
return retValue;
8489
}
8590

@@ -120,11 +125,16 @@ public int size() {
120125
* Clear all nodes in queue
121126
*/
122127
public void clear() {
123-
//TODO
128+
while (!isEmpty()) {
129+
dequeue();
130+
}
124131
}
125132

126133
@Override
127134
public String toString() {
135+
if (isEmpty()) {
136+
return "[]";
137+
}
128138
StringBuilder builder = new StringBuilder();
129139
Node cur = front.next;
130140
builder.append("[");
@@ -144,11 +154,16 @@ public static void main(String[] args) {
144154
queue.enqueue(1); /* 1 */
145155
queue.enqueue(2); /* 1 2 */
146156
queue.enqueue(3); /* 1 2 3 */
147-
System.out.println(queue);
157+
System.out.println(queue); /* [1, 2, 3] */
148158

149159
assert queue.size() == 3;
150160
assert queue.dequeue() == 1;
151161
assert queue.peekFront() == 2;
152162
assert queue.peekRear() == 3;
163+
164+
queue.clear();
165+
assert queue.isEmpty();
166+
167+
System.out.println(queue); /* [] */
153168
}
154169
}

0 commit comments

Comments
 (0)