#include "cHash.h"

template <class T> cHash<T>::cHash(){
	Items = 0;
	Table = NULL;
	Exist = NULL;
}
template <class T> cHash<T>::cHash(int nItems){
	Create(nItems);
}

template <class T> cHash<T>::~cHash(){
	Destroy();
}

template <class T> bool cHash<T>::Create(int n){
	Items = n;
	Table = new T[Items];
	if(!Table) return false;
	Exist = new bool[Items];
	if(!Exist){
		delete [] Table;
		return false;
	}
	for(int i = 0; i < Items; i ++)
		Exist[i] = false;
	return true;
}
template <class T> void cHash<T>::Destroy(){
	if(Items){
		delete [] Table;
		delete [] Exist;
		Items = 0;
	}
}
///////////////////////////////////////
template <class T> bool cHash<T>::IsIn(T &A){
	int Index, i;

	Index = A.GetHashNumber();
	for(i = 0; i < Items; i ++){
		if((Index - i >= 0) && Exist[Index - i]){
			if(Table[Index - i] == A) return true;
		}else if((Index + i < Items) && Exist[Index + i]){
			if(Table[Index + i] == A) return true;
		}
	}
	return false;
}

template <class T> bool cHash<T>::Get(T &A){
	int Index, i;
	Index = A.GetHashNumber();
	for(i = 0; i < Items; i ++){
		if((Index - i >= 0) && Exist[Index - i] && Table[Index - i] == A){
			A = Table[Index - i];
			return true;
		}else if((Index + i < Items) && Exist[Index + i] && Table[Index + i] == A){
			A = Table[Index + i];
			return true;
		}
	}
	return false;
}
template <class T> bool cHash<T>::Insert(T &A){
	int Index, i;

	Index = A.GetHashNumber();
	if(!Exist[Index]){
		Table[Index] = A;
		Exist[Index] = true;
		return true;
	}else{
		// Find Empty Node then Insert It
		for(i = 1; i < Items; i ++){
			if((Index - i >= 0) && !Exist[Index - i]){
				Table[Index - i] = A;
				Exist[Index - i] = true;
				return true;
			}else if((Index + i < Items) && !Exist[Index + i]){
				Table[Index + i] = A;
				Exist[Index + i] = true;
				return true;
			}
		}
	}
	return false;
}
template <class T> bool cHash<T>::Delete(T &A){
	int Index, i;

	Index = A.GetHashNumber();
	for(i = 0; i < Items; i ++){
		if((Index - i >= 0) && Exist[Index - i]){
			if(Table[Index - i] == A) Exist[Index - i] = false;
			return true;
		}else if((Index + i < Items) && Exist[Index + i]){
			if(Table[Index + i] == A) Exist[Index + i] = false;
			return true;
		}
	}
	return false;
}
/////////////////////////////////////////////////////
