1

Java でリンク キューを実装しています。ただし、コードを実行するとエラーが発生します。

public class LinkedQueue<E> implements Queue<E> {
   private int count;
   private Node<E> front, rear;

   public LinkedQueue() {
      count = 0;
      front = rear = null;
   }

   public void enqueue (E element) {
      Node<E> node = new Node<E> ();

      if (isEmpty())
         front = node;
      else
         rear.setNext (node);

      rear = node;
      count++;
   }

   public E dequeue() throws QueueEmptyException {
      if (isEmpty())
         throw new QueueEmptyException  ("queue");

      E result = front.getElement();
      front = front.getNext();
      count--;

      if (isEmpty())
         rear = null;

      return result;

   }

   public E first() throws QueueEmptyException {
      if (isEmpty())
         throw new QueueEmptyException ("queue"); 

      return front.getElement();
   }


   public boolean isEmpty() {
      return (front == rear);
   }


   public int size() {
      return count;
   }


    public E front() throws QueueEmptyException {       
        if (isEmpty())
            throw new QueueEmptyException("Queue underflow.");
        return (E) front.getNext();
    }
}

LinkedQueue のどこが悪いのか、永遠に構成してきました。コードの修正を手伝ってください。私はJavaが初めてで、構文エラーが原因である可能性があります。

4

5 に答える 5

2

java.util.LinkedList ジェネリック クラスから Queue のすべての機能を使用できます。要素をキューに入れるには addLast メソッドを使用し、要素をキューから取り出すには removeFirst メソッドを使用します。LinkedList は二重にリンクされているため、Queue のすべてのパフォーマンス上の利点を確認できます。

于 2012-07-17T13:55:46.047 に答える
1

java.util.LinkedListをすでに実装していQueueます。
なぜそれを使用しないのですか?

Queue<T> queue = new LinkedList<>();
于 2012-07-17T13:53:56.070 に答える
0

あなたの enqueue() メソッドは、渡された要素に対して何もしません。おそらくそれを Node のコンストラクターに渡したいですか?

于 2012-07-17T13:53:43.220 に答える
0

これは非常に疑わしいように見えます:

public void enqueue (E element) {
  Node<E> node = new Node<E> ();

  if (isEmpty())
     front = node;
  else
     rear.setNext (node);

  rear = node;
  count++;

}

パラメータelementは使用されません。試す

Node<E> node = new Node<E> (element);

か何か。

于 2013-05-31T13:19:35.180 に答える