hash表2 Java

package hash;

public class HashSet {
	private static int maxsize=100;
	public Node []hashtable;
	private boolean []flagtable; // 0: no data; 1: data inside; 
	public HashSet(){
		hashtable = new Node[maxsize];
		flagtable = new boolean[maxsize];
		for (int i=0;i<maxsize;i++)
			flagtable[i]=false;
	}
	
	private static final int HashConv(String key){
//		System.out.println(key+"'s hash is "+key.hashCode());
		int i = (key.hashCode()) & (maxsize-1);
		return i;
	}
	
	public boolean Insert(Node t){
		int pos = HashConv(t.GetKey());
		int cnt = 0;
		boolean flag = false;
		while(flagtable[pos]){
			pos = ReHash(cnt,pos);
			if(cnt==maxsize)
				break;
			cnt++;
		}
		if(!flagtable[pos])
			{
				hashtable[pos]=t;
				flag = true;
				flagtable[pos]=true;
			}
		return flag;
	}
	
	public int ReHash(int cnt,int pos){
		pos = (pos + 1 + cnt*cnt)%(maxsize);
		return pos;
	}
	
	
	public int Find(String key)
	{
		int pos = HashConv(key);
		int mypos = -1;
		int cnt = 0;
		while(cnt != maxsize){
			if(flagtable[pos] && key==hashtable[pos].GetKey()){
				mypos = pos;
				break;
			}
			else
			{
				pos = ReHash(cnt,pos);
				cnt++;
			}
		}
		//System.out.println(key+" is found at "+mypos);
		return mypos;
	}
	
	public boolean Delete(String key){
		int pos = Find(key);
		if(-1==pos)
		{
			System.out.println("No Node with key "+key+" indside!");
			return false;
		}
		else if (pos>=maxsize)
		{
			System.out.println("Node with key "+key+" in pos "+pos+" !\n Error!");
			return false;			
		}
		else{
			flagtable[pos]=false;
			System.out.println(key+" is deleted at "+pos);
			return true;
		}
	}
	
	public void Show(){
		for (int i =0;i<maxsize;i++){
			if(flagtable[i])
				System.out.println(hashtable[i].GetKey()+" : "+hashtable[i].GetValue());
		}
	}
	
	
	
	public static void main(String []args){
		HashSet myhashset = new HashSet();
		myhashset.Insert(new Node("ZhuGuanya",614));
		myhashset.Insert(new Node("XuTingyu",647));
		myhashset.Insert(new Node("YuXiaolong",675));
		myhashset.Show();
		int pos = myhashset.Find("ZhuGuanya");
		System.out.println("ZhuGuanya is found at pos "+pos);
		myhashset.Delete("Yuxiaolong");
		myhashset.Delete("YuXiaolong");
		myhashset.Delete("ZhuGuanya");
		pos = myhashset.Find("ZhuGuanya");
		System.out.println("ZhuGuanya is found at pos "+pos);
		myhashset.Show();
	}

}


package hash;

public class Node {
	private String   key;
	private int   value;
	public Node()
	{
		key = "";
		value = -1;
	}
	public Node(String i,int j)
	{
		key = i;
		value = j;
	}
	public int GetValue()
	{
		return value;
	}
	public String GetKey()
	{
		return key;
	}
	public void SetValue(int value){
		this.value = value;
	}
	public void SetKey(String key){
		this.key = key;
	}

}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值