`
sillycat
  • 浏览: 2542930 次
  • 性别: Icon_minigender_1
  • 来自: 成都
社区版块
存档分类
最新评论

Interview(8)Dictionary and Tree

 
阅读更多
Interview(8)Dictionary and Tree

Dictionary - No Order
public class DictionaryDLNode implements Dictionary {
    private List list; //store all items
    private EqualityTester tester;

    public DictionaryDLNode(){
        this(new EqualityTesterDefault());
    }

    public DictionaryDLNode(EqualityTester t){
        list = new ListDLNode(); tester = t;
    }

    public int getSize() { return list.getSize(); }
   
    public boolean isEmpty() { return list.isEmpty(); }

    public Entry find(Object key){
        Iterator p = list.positions();
        while(p.hasNext()){
            Position pos = (Position) p.getNext();
            Entry entry = (EntryDefault) pos.getElem();
            if(tester.isEqualTo(entry.getKey(), key)){
                return entry;
            }
        }
    }

    public Iterator findAll(Object key){
        List list = new ListDLNode();
        Iterator p = l.positions();
        while(p.hasNext()){
            Position pos = (Position)p.getNext();
            Entry entry = (EntryDefault) pos.getElem();   
            if(tester.isEqualTo(entry.getKey(), key)){
                list.insertLast(entry);
            }
        }
        return new IteratorElement(list);
    }

    public Entry insert(Object key, Object value){
        Entry entry = new EntryDefault(key, value); //create new Entry
        list.insertFirst(entry);
        return entry;
    }

    public Entry remove(Object key){
        Iterator p = list.positions();
        while(p.hasNext()){
            Position pos = (Position) p.getNext();
            Entry entry = (EntryDefault) pos.getElem();
            if(tester.isEqualTo(entry.getKey()), key){
                Entry oldEntry = entry;
                list.remove(pos); //remove item
                return oldEntry;
            }
        }
        return null;
    }

    public Iterator entries() { return new IteratorElement(list); }
}

Dictionary - Order
Binary Search

Method: binSearch(S, low, high, key)
Inputs: search table S, low and high, Key
Outputs: s[low.. high], find the item for key

binSearch(S, 0, n-1, key)
{
    if low > high, system can not find it
    middle = (low + high) /2;
    if key > S[middle].key, binSearch(S, middle+1, high, key);
    if key < S[middle].key, binSearch(S, low, middle-1, key);
    return middle; //hit the right item
}

Binary Search Tree
left tree should be lower than current parent key, right tree should be higher than current parent key.

AVL Tree

B Tree - TODO

Sorting



References:


分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics