2012-10-08 40 views
0

這些都是我的領域:迭代方法BST

public class BSTSet <E> extends AbstractSet <E> { 

    // Data fields 
    private BSTNode root; 
    private int count = 0; 
    private Comparator<E> comp; // default comparator 

    /** Private class for the nodes. 
    * Has public fields so methods in BSTSet can access fields directly. 
    */ 
    private class BSTNode { 

     // Data fields 

     public E value; 
     public BSTNode left = null; 
     public BSTNode right = null; 

     // Constructor 

     public BSTNode(E v) { 
      value = v; 
     } 

     //creates a method called contains so that i can call it later on for my find method 
     public boolean contains(Object item) { 
      return contains(item);//root.value.equals(item); 
     } 

     public int height() { 
      return height(); 
     } 

    } 
    // Constructors - can either use a default comparator or provide one 
    public BSTSet() { 
     comp = new ComparableComparator();  // Declared below 
    } 

    public BSTSet(Comparator <E> c) { 
     comp = c; 
    } 
} 

,這就是我試圖完成:

private class BSTSetIterator implements Iterator<E> { 

    private Stack<BSTNode> stack = new Stack<BSTNode>(); 
    private BSTNode current = root; 

    public BSTSetIterator(BSTNode root) { 

     return new BSTSetIterator(); 

    } 

    public boolean hasNext() { 

     boolean hasNext = false; 
     hasNext = !stack.isEmpty() || current != null; 
     return hasNext; 

    } 

    public E next() { 

     BSTNode next = null; 

     while (current != null) { 
      stack.push(current); 
      current = current.left; 
     } 
     next = stack.pop(); 
     current = next.right; 

     return next; 

    } 

    public void remove() { 
     throw new UnsupportedOperationException(); 
    } 
} 
// Comparator for comparable 

private class ComparableComparator implements Comparator<E> { 
    public int compare(E ob1, E ob2) { 
     return ((Comparable)ob1).compareTo(ob2); 
    } 
} 

到目前爲止,代碼失敗的行return new BSTSetIterator();return next;。對於return next,它表示它返回的數據類型是錯誤的。我將如何去修復這些方法,以便我可以使用堆棧遍歷BST?

+0

如何將您的班級更改爲'私人班級BSTSetIterator implements Iterator ' – gtgaxiola

回答

2
BSTSetIterator(); 

這不起作用,因爲您的構造函數需要一個根,並且您沒有傳遞該參數。如果你有一個叫做「樹」一BSTSet對象,你要創建一個新的迭代器,那麼你應該創建一個迭代是這樣的:

BSTSetIterator iterator = new BSTSetIterator(tree.getRoot()); 

但是,你沒有一個getter在BSTSet類你的根是私人的。別擔心,該問題的解決方案是創建一個公共的getter你BSTSetIterator類裏,像這樣:

public BSTNode getRoot() 
{ 
    return this.root; 
} 

構造函數沒有返回值,這是不正確的:

public BSTSetIterator(BSTNode root) { 
     return new BSTSetIterator(); 
    } 

相反,寫你的construtor這樣:

public BSTSetIterator(BSTNode root) 
{ 
    this.current = root; 
} 

而且,這個定義是不正確的,因爲根本是遙不可及:

private BSTNode current = root; 

你應該有這個代替:

private BSTNode current; 

至於你的其他問題,

BSTNode next = null; 

意味着你的變量稱爲 '下一個' 是BSTNode類型。

public E next() 

意味着您的next方法是E型。由於E和BSTNode不一樣,您的退貨:

return next; 

不正確。我可以給你更多的幫助,但是我意識到你現在正在學習語言,最好讓你自己探索一下技術和編程,因爲這樣你會變得更快。 「給一個人一條魚,然後你喂他一天,教一個人如何去釣魚,並且你一輩子喂他。」