java - 如何仅使用后部外部指针使这个链接队列循环?

标签 java linked-list queue circular-list

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;
// otherwise, 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 class CircLinkedUnbndQueue<T> implements UnboundedQueueInterface<T>
{
  protected LLNode<T> rear;    // reference to the rear of this queue

  public CircLinkedUnbndQueue()
  {
    rear = null;
  }

  public void enqueue(T element)
  // Adds element to the rear of this queue.
  { 
    LLNode<T> newNode = new LLNode<T>(element);

    if (rear == null)
    {
      rear = newNode;
    }
    else
    {   
      //links the newNode to the rear node's pointer and then 're'points the 
      //rear node to the newNode.
      if(rear.getLink() == null)
      {
        rear.setLink(newNode);
        newNode.setLink(rear);
      }
      else
      {
        newNode.setLink(rear.getLink());
        rear.setLink(newNode);
      }
    }
      //'repositions' the reat node at the end of the queue.
      rear = newNode;
    }  

  public T dequeue()
  // Throws QueueUnderflowException if this queue is empty;
  // otherwise, removes front element from this queue and returns it.
  {
    if (isEmpty())
      throw new QueueUnderflowException("Dequeue attempted on empty queue.");
    else
  {
      T element;

      rear = rear.getLink();
      element = rear.getInfo();

      if (rear.getLink() == null)
        rear = null;

      return element;
    }
  }

  public boolean isEmpty()
  // Returns true if this queue is empty; otherwise, returns false.
  {              
    if (rear == null) 
      return true;
   else
      return false;
  }
}

我知道这是一篇旧帖子,但我最近遇到了这个问题,并且相信这更符合所提出的问题,因为它仅使用后节点。

关于java - 如何仅使用后部外部指针使这个链接队列循环?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4357798/

相关文章:

java - Accumulo 表扫描器在 Java 中静默失败

java - 如何获取从最后一个元素开始的前向迭代器

c - C 中带有链表和计数器的队列

c# - 从 Windows 服务处理长时间运行的操作

java - JUnit assertFalse(true) --> 成功的测试用例?

java - 如何 jetty 化maven项目?有多少种方法来完成它?

java - 致命异常主要

C 编程中的代码安全(避免任何分段/错误)

Java的Queue不能指定有限的大小,那么 "add"和 "offer"有什么区别

c++ - for std::queue remove all of element swap 和 pop 的时间差