2009-08-08 6 views
0

dequeに非常に短いコードを書く必要がありますが、メソッドのコードを書く方法がわかりません。 dequeの元にオブジェクトを追加してください)、それが私の仕事を開始します。残りのメソッドを管理できると確信しています。ちょうど私がかなり困惑している瞬間です。LinkedListのような既存のクラスを使用しないJava Deque?

+0

なぜあなたはこれをやっていますか?標準のDeque実装の1つを使用すると何が問題になりますか? –

答えて

2

私はあなたが後にしている正確にわからないんだけど、のDequeのために利用可能な方法は、通常、二重リンクリストとして実装されているJavadoc

6

Dequeとに記載されています。リストの最初と最後の要素を追跡し、各要素にその前身と後継者を追跡させることによって、二重リンクされたリストを実装します。

public class Deque<T> { 
    private class Node { 
     Node(T value) { 
      this.value = value; 
     } 
     T value; 
     Node next, prev; 
    } 

    private Node first, last; 

    public void addFront(T value) { 
     Node oldFirst = first; 
     first = new Node(value); 

     // The old first item is now the second item, so its the successor of 
     // the new first item 
     first.next = oldFirst; 

     // if first was null before, that means the deque was empty 
     // so first and last should both point to the new item 
     if(oldFirst == null) { 
      last = first; 
     } else { 
      // If there previously was a first element, this element is 
      // now the second element and its prev field should point to 
      // the new first item 
      oldFirst.prev = first; 
     } 
    } 
} 
関連する問題