2011-04-14 30 views
0

我需要在這兩個類實現一個尺寸()和真的不知道如何開始:鏈表的大小()

interface Tree extends Cloneable { 
    int size(); 
} 

class Fruit implements Tree { 

    @Override public int size() { 

    } 
} 

class Branch implements Tree { 

    private List<Tree> children = new LinkedList<Tree>(); 
    public List<Tree> getChildren() { 
     return Collections.unmodifiableList(children); 
    } 

    public void addChild(Tree tree) { 
     children.add(tree); 
    } 

    @Override public int size() { 

    } 
} 

任何人都可以指導我在正確的方向上如何創建這兩個尺寸() 方法?我需要他們來計算樹中實際水果的數量。

+1

這不是一個鏈表。那是一棵樹。 – 2011-04-14 17:26:42

+0

public class Fruit implements Tree { \t @Override public int size(){ \t \t return this.size(); \t \t \t}} 公共類分公司實現樹{ \t私人列表孩子=新的LinkedList (); \t public List getChildren(){return Collections.unmodifiableList(children); } \t public void addChild(Tree tree){children.add(tree); } \t @Override public int size(){ \t \t return this.getChildren()。size(); \t} } – Alpdog14 2011-04-14 17:42:23

回答

3

我認爲這是作業嗎? ;)

如何

@Override public int size() { 
    int size = 0; 
    for(Tree tree: children) size += tree.size(); 
    return size; 
} 
+0

我離開Fruit的實現作爲練習。我不能完成他的所有功課;)我假定「樹上的實際水果數量」。只意味着水果而不是分支應該被計算在內。 – 2011-04-14 17:24:29

+0

啊,你說得對。我以爲他想統計節點,並沒有仔細考慮這個問題。 – 2011-04-14 17:29:15

+0

所以對於水果,我會做一些簡單的事情:return this.size(); – Alpdog14 2011-04-14 17:47:58

0

鏈表操作以遞歸的方式,在每一個節點都有這個定義尺寸爲典型的做法:

@Override 
public int size(){ 
    // Don't forget the base case! (if there is no child) 
    return (child != null) ? 1 + child.size() : 1; 
} 

呼叫,rootNode.size(),遞歸總結1對於鏈表的每個節點,並最終將大小返回給原始調用者。