1. 程式人生 > >雜湊表—拉鍊法

雜湊表—拉鍊法

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));
	}
}