算法 3.4节 两种哈希树的实现

  • 链表对象
public class LinkedList<Key,Value> {
    private Node first;

    private class Node {
        Key key;
        Value val;
        Node next;

        public Node(Key key, Value val, Node next) {
            this.key = key;
            this.val = val;
            this.next = next;
        }
    }

    public Value get(Key key) {
        for (Node x = first; x != null;x = x.next) {
            if (key.equals(x.key)) return x.val;
        }
        return null;
    }

    public void put(Key key, Value val) {
        for (Node x = first; x != null;x = x.next) {
            if (key.equals(x.key)) {
                x.val = val;
                return;
            }
        }
        first = new Node(key,val,first); // 从头部加入新节点
    }


}
  • 链表法

public class HashTree <Key,Value>{ //泛型
    private int Num;
    private int capacity;
    private LinkedList<Key,Value>[] ht;

    public HashTree() {
        this(1);
    }

    public HashTree(int capacity) {
        ht = (LinkedList<Key,Value>[]) new LinkedList[capacity];
        this.capacity = capacity;
        for (int i =0;i < capacity;i++)
            ht[i] = new LinkedList<Key,Value>();
    }

    private int hash(Key key) {
        return (key.hashCode() & 0x7ffffffff) % capacity;
    }

    public Value get(Key key) {
        return ht[ hash(key)].get(key);
    }

    public void put(Key key, Value value) {
        Num++;
        ht[hash(key)].put(key,value);
    }

}
  • 开放地址法
public class AnotherHashTree <Key,Value>{ //泛型
    private int Num;
    private int capacity;
    private Value[] values;
    private Key[] keys;

    public AnotherHashTree() {
        this(1);
    }

    public AnotherHashTree(int capacity) {
        values = (Value[]) new Object[capacity];
        keys = (Key[]) new Object[capacity];
    }

    private int hash(Key key) {
        return (key.hashCode() & 0x7ffffffff) % capacity;
    }

    public Value get(Key key) {
        int i =hash(key);
        while (keys[i] != null) {
            if (keys[i].equals(key) ) return values[i]; //用equal比用=要好,因为有的类型可能不能直接比较
            else i = (i+1) % capacity;
        }
        return null;
    }

    public void put(Key key, Value value) {
        int i = hash(key);
        while (keys[i] != null && !keys[i].equals(key)) i = (i+1) %capacity;
        keys[i] = key;
        values[i] = value;
        Num++;
        if(Num > capacity/2) resize(2*capacity);
    }

    private void resize(int capacity) {
        AnotherHashTree<Key,Value> temp =new AnotherHashTree<Key,Value>(capacity);
        for (int i = 0;i<capacity;i++) {
            temp.put(keys[i],values[i]);
        }
        this.keys = temp.keys;
        this.values = temp.values;
        this.capacity  = temp.capacity;
    }

}

    原文作者:哈希算法
    原文地址: https://blog.csdn.net/winter_wu_1998/article/details/79555936
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞