开发者

How would this code in java be changed to make it a circular queue using linked list?

开发者 https://www.devze.com 2023-01-28 16:48 出处:网络
Using only the rear external pointer public void enqueue(Object element) // Adds element to the rear of this queue.

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
  }
...
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号