2017-05-01 2 views

答えて

0

Nileshが指摘したように、キューはインデックスで使用されることは意図されていません。とにかく、Queueとiteratorを使って独自のクラスを実装し、インデックスで要素を見つけることができます。それは場合、あなたが探している場合は、次の例を考えてみてください。

public class QueueExample<E> { 

    private Queue<E> queue = new LinkedList<>(); 

    public void add(E item) { 
     queue.add(item); 
    } 

    public E peek(int index) { 
     E item = null; 
     Iterator<E> iterator = queue.iterator(); 
     while (iterator.hasNext()) { 
      E temp = iterator.next(); 
      if (index-- == 0) { 
       item = temp; 
       break; 
      } 
     } 
     return item; 
    } 

    public static void main(String[] args) { 
     QueueExample<String> queueExample = new QueueExample<>(); 
     queueExample.add("One"); 
     queueExample.add("Two"); 
     queueExample.add("Three"); 

     System.out.println(queueExample.peek(0)); 
     System.out.println(queueExample.peek(2)); 
     System.out.println(queueExample.peek(1)); 
     System.out.println(queueExample.peek(4)); 
    } 
} 

出力を(予想通り):

One 
Three 
Two 
null 

・ホープ、このことができます。

+0

ええ、これはトリックを行う必要があります。ただし、問題のあるのは、最悪の場合のパフォーマンスがO(n)であるのに対し、より適切なデータ構造(リストなど)を使用すると、最初にO(1)の実行時間 –

0

キューの設計では、それを行うことはできません。キューのヘッダだけを見ることができます。

インデックスで要素にアクセスする場合は、[キュー]の代わりに[リスト]を使用します。

関連する問題