I use a circular linked list to implement a queue
, and it only holds one last
(note that last.next
links to the first
, not null
).
public class Queue<T> {
private Node last;
private int n;
private class Node {
T value;
Node next;
Node(T t, Node n) {
value = t;
next = n;
}
}
public Queue() {
last = null;
n = 0;
}
public boolean isEmpty() {
return n == 0;
}
public void enqueue(T item) {
if (isEmpty()) {
last = new Node(item, null);
last.next = last;
} else {
Node tmp = new Node(item, last.next);
last.next = tmp;
last = tmp;
}
n++;
}
// other code
}
I think the correct way of dequeue()
is :
public T dequeue() {
if (isEmpty()) throw new NoSuchElementException();
Node first = last.next;
T t = first.value;
if (last == first) {
last = null;
} else {
last.next = first.next;
}
n--;
return t;
}
This is because we should set last
to null
if there is one element.
However, the alternative way in following also works, why?
public T dequeue2() {
if (isEmpty()) throw new NoSuchElementException();
Node first = last.next;
T t = first.value;
last.next = first.next;
n--;
return t;
}
I call N
times dequeue2()
after N
times enqueue()
, and assert queue.last== null
. To my surprize, the assertion passes. I think the last
can never be null
if I use dequeue2()
.
So, is the dequeue2()
correct?