用拉链法实现哈希算法的运算

package lirui.find;

import java.util.LinkedList;

/**
 * Created by lirui on 14-8-13.
 * 用拉链法实现哈希算法的运算
 */
public class MyHashSearch2 {
    public static final int SIZE = 10;
    public static MyHashElement[] hashtable = new MyHashElement[SIZE];

    // 记录hash表中的数量。
    public static int count = 0;

    // 哈希函数  h(key)= key mod p
    public static int hashFunction(int key, int p) {
        return key % p;
    }

    // 将key插入到哈希表中
    public static void insertHT(MyHashElement[] hashTable,int key, int p) {
        int adr;
        adr = hashFunction(key, p);
        // 当没有冲突发生的时候,说明还没有存过。
        if (hashTable[adr] == null){
            hashTable[adr] = new MyHashElement();
            hashTable[adr].setKey(new LinkedList<Integer>());
            hashTable[adr].getKey().add(key);
        } else {
            // 当发生冲突,说明已经有链表了,则直接存入。
            hashTable[adr].getKey().add(key);
        }
        count++;
    }

    /**
     * @param hashTable
     * @param x          要存入哈希表中的数组
     * @param p          哈希参数
     */
    public static void createHT(MyHashElement[] hashTable, int[] x, int p) {
        int i, length = x.length;
        for (i = 0; i < length; i++) {
            insertHT(hashtable, x[i], p);
        }
    }


    // 查找
    /**
     *
     * @param hashtable
     * @param key 待查的数字
     * @return 返回地址值
     */
    public static int searchHT(MyHashElement[] hashtable,int key,int p){
        int address = hashFunction(key,p);
        if (hashtable[address] == null){
            return -1;
        } else {
            // 从链表里搜索
            if (hashtable[address].getKey().contains(key)){
                    return address;
            } else{
                return  -1;
            }
        }
    }
    public static void main(String[] args) {
        int[] x = {7, 8, 30, 11, 18, 9 ,14};
        createHT(hashtable,x,7);
        for (MyHashElement hashElement : hashtable) {
            if (hashElement !=null){
                for (Integer i : hashElement.getKey()) {
                    System.out.print(i + "      ");
                }
                System.out.println();
            }
        }
        System.out.println(searchHT(hashtable,14,7));
        System.out.println(searchHT(hashtable,2333,7));
    }
}

class MyHashElement {
    LinkedList<Integer> key; //元素关键字,是一个链表
    String info; // 元素信息

    public void setKey(LinkedList<Integer> key) {
        this.key = key;
    }

    MyHashElement() {
    }
    public LinkedList<Integer> getKey(){
        return  key;
    }
    MyHashElement(LinkedList<Integer> list, String info) {
        this.key = list;
        this.info = info;
    }
}

自己写的用拉链法实现哈希算法的运算

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