码迷,mamicode.com
首页 > 其他好文 > 详细

散列的链表实现

时间:2017-09-28 20:40:17      阅读:151      评论:0      收藏:0      [点我收藏+]

标签:val   hlist   ash   for   make   private   htable   散列   ret   

public class SeparateChainingHashTable<T> {
  public  SeparateChainingHashTable(){
    this(DEFAULT_TABLE_SIZE);
  }
  public  SeparateChainingHashTable(int size){
      theLists=new LinkedList[nextPrime(size)];
      for(int i=0;i<theLists.length;i++){
          theLists[i]=new LinkedList<T>();
      }
  }
  public void insert(T val){
      List<T> whichList=theLists[myhash(val)];
      if(!whichList.contains(val)){
          whichList.add(val);
          if(++currentSize>theLists.length){
              rehash();
          }
      }
  }
  public void makeEmpty(){
      for(int i=0;i<theLists.length;i++){
           theLists[i].clear();
          }
      currentSize=0; 
  }
  public void remove(T val){
      List<T> whichList=theLists[myhash(val)];
      if(whichList.contains(val)){
            whichList.remove(val);
           currentSize--;
      }
            
  }
  public boolean contains(T val){
     List<T> whichList=theLists[myhash(val)];
    return  whichList.contains(val);
    
  }

  private static final int DEFAULT_TABLE_SIZE=101;
  private List<T>[] theLists;
  private int currentSize;
  private void rehash(){
      
  }
  private int myhash(T val){
      int hashVal=val.hashCode();
      hashVal%=theLists.length;
      if(hashVal<0){
          hashVal+=theLists.length;
      }
      return hashVal;
  }
  private static int nextPrime(int n){
      boolean state=isPrime(n);  
        while(!state)  
        {  
            state=isPrime(++n);  
      
        }  
        return n;  
  }
  private static boolean isPrime(int n){
       if ( n==1 || n ==4 )
            return false;
        if ( n ==2 || n== 3 )
            return true;
          //num从5开始进入循环,以保证√n>=2,循环不会被跳过
        for ( int i = 2; i<= Math.sqrt( n ); i++ )
        {
            if ( n% i==0 )
                return false;
        }
        
        return true;    
  }
}

 

散列的链表实现

标签:val   hlist   ash   for   make   private   htable   散列   ret   

原文地址:http://www.cnblogs.com/wxw7blog/p/7608303.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!