哈希表—拉链法

public class Link {
	/**
	 * 有序链表链接点
	 */
   public int data;
   public Link nextLink;
   public Link(int data){
	   this.data = data;
   }
   public int getKey(){
	   return data;
   }
@Override
public String toString() {
	return "Link [data=" + data + "]";
}
}


package Hash;

public class OrderList {
   /**
    * 有序链表的实现    从小到大的有序链表的实现
    */
    private Link first;
    public OrderList(){
    	first = null;
    }
    public boolean isEmpty(){
    	return first == null;
    }
    /**
     * 插入新的值
     */
    public void insert(int key){
    	Link link = new Link(key);
    	Link previous = null;
    	Link current = first;
    	while(current!=null&&current.data<key){
    		//如果当前的值小于Key 那么就继续向下遍历
    		previous = current;
    		current = current.nextLink;
    	}
    	if(previous == null){
    		first = link;
    	}else{
    		previous.nextLink = link;
    	}
    	link.nextLink = current;
    }
    //根据值  找位置
    public Link find(int key){
    	Link current = first;
    	while(current!=null&&current.data!=key){
    		current = current.nextLink;
    	}
    	return current;
    }
    //根据值删除一个节点
    public void delete(int key){
    	Link previous = null;
    	Link current = first;
    	while(current !=null && key!=current.getKey()){
    		previous = current;
    		current = current.nextLink;
    	}
    	if(previous == null){
    		first = first.nextLink;
    	}else{
    		previous.nextLink = current.nextLink;
    	}
    }
    public void display(){
    	Link current = first;
    	while(current!=null){
    		System.out.print(current.data+" ");
    		current = current.nextLink;
    	}
    	System.out.println();
    }
}


public class HashChain {
  /**
   * 拉链法
   * 拉链法 就是哈希表里面的每个单元中设置链表,数据映射到某个单元上之后直接插入到链表中即可。不用在寻扎空位置
   *    orderlist类型的数组
   *    数组中存储链表List
   *    list里面存储对象
   */
	private OrderList[] hashArray;
	private int arraySize;
	public HashChain(int size){
	    arraySize = size;
	    hashArray = new OrderList[size];
	    for(int i=0;i<hashArray.length;i++){
	    	hashArray[i] = new OrderList();
	    }
	}
	//打印hash表
	public void displayTable(){
		for(int i=0;i<arraySize;i++){
			System.out.print(i+" ");
			hashArray[i].display();
		}
	}
	
	public int hashFun(int key)
	{
		return key%arraySize;
	}
	
	//哈希插入
	public void insert(int key){  //将key相同的值 插入到同一个链表中
		int hashVal = hashFun(key);
		hashArray[hashVal].insert(key);
	}
	//哈希删除
	public void delete(int key){
		int hashVal = hashFun(key);
		hashArray[hashVal].delete(key);
	}
	//哈希查找
	public Link Find(int key){
		int hashVal = hashFun(key);
		Link theLink = hashArray[hashVal].find(key);
		return theLink;
	}
	public static void main(String[] args) {
		HashChain Hc = new HashChain(5);
		Hc.insert(1);
		Hc.insert(5);
		Hc.insert(8);
		Hc.insert(2);
		Hc.insert(10);
		Hc.displayTable();
		System.out.println(Hc.Find(5));
	}
}

猜你喜欢

转载自blog.csdn.net/qq_39536716/article/details/83046208