Skip to content
Merged
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Prev Previous commit
update LinkedQueue
  • Loading branch information
realDuYuanChao committed Oct 24, 2019
commit fce3d838dbf0cb729bc4e1eb0309a1cafca0d1a5
19 changes: 17 additions & 2 deletions DataStructures/Queues/LinkedQueue.java
Original file line number Diff line number Diff line change
Expand Up @@ -80,6 +80,11 @@ public int dequeue() {
front.next = front.next.next;
destroy = null; /* clear let GC do it's work */
size--;

if (isEmpty()) {
front = rear;
}

return retValue;
}

Expand Down Expand Up @@ -120,11 +125,16 @@ public int size() {
* Clear all nodes in queue
*/
public void clear() {
//TODO
while (!isEmpty()) {
dequeue();
}
}

@Override
public String toString() {
if (isEmpty()) {
return "[]";
}
StringBuilder builder = new StringBuilder();
Node cur = front.next;
builder.append("[");
Expand All @@ -144,11 +154,16 @@ public static void main(String[] args) {
queue.enqueue(1); /* 1 */
queue.enqueue(2); /* 1 2 */
queue.enqueue(3); /* 1 2 3 */
System.out.println(queue);
System.out.println(queue); /* [1, 2, 3] */

assert queue.size() == 3;
assert queue.dequeue() == 1;
assert queue.peekFront() == 2;
assert queue.peekRear() == 3;

queue.clear();
assert queue.isEmpty();

System.out.println(queue); /* [] */
}
}