Using only the rear external pointer
public void enqueue(Object element)
// Adds element to the rear of this queue.
{
LLObjectNode newNode = new LLObjectNode(element);
if (rear == null)
front = newNode;
else
rear.setLink(newNode);
rear = newNode;
}
public Object dequeue()
// Throws QueueUnderflowException if this queue is empty;
// o开发者_Python百科therwise, removes front element from this queue and returns it.
{
if (isEmpty())
throw new QueueUnderflowException("Dequeue attempted on empty queue.");
else
{
Object element;
element = front.getInfo();
front = front.getLink();
if (front == null)
rear = null;
return element;
}
}
public boolean isEmpty()
// Returns true if this queue is empty; otherwise, returns false.
{
if (front == null)
return true;
else
return false;
}
public void enqueue(Object element)
...
rear.setLink(newNode);
rear = newNode;
rear.setLink(front); // make circular
}
...
public Object dequeue()
...
Object element;
element = front.getInfo();
if (front.getLink() == front) {
// break circle for last element
front = null;
rear = null;
} else {
front = front.getLink();
rear.setLink(front); // make circular
}
...
精彩评论