public class ChainingHash<Key,Value>{
private int N;
private int M;
private doublylinked<Key,Value>[] s;
public ChainingHash(int M){
this.M = M;
s = new doublylinked [M];
for(int i=0;i<M;i++){
s[i] = new doublylinked();
}
} public int hash(Key key){
return (key.hashCode() & 0x7fffffff)%M;
} private void put(Key key,Value val){
s[hash(key)].put(key, val);
} private Value get(Key key){
return s[hash(key)].get(key);
} private void delet(Key key){
s[hash(key)].delet(key);
} public void print(){
for (int i = 0;i<M;i++){
s[i].print();
System.out.println(" ");
}
} public class doublylinked<Key,Value>{
private Node first;
public doublylinked(){
first = null;
}
private class Node{
Key key;
Value val;
Node next,last;
public Node(Key key,Value val,Node next,Node last){
this.key = key;this.val = val;this.next = next; this.last = last;
}
}
public void put(Key key,Value val){
for(Node x = first;x!= null;x= x.next){
if(key.equals(x.key)){
x.val = val;
return;
}
}
if(first == null){
first = new Node(key,val,null,null);
}
else{
first.last = new Node(key,val,first,null);
first = first.last;
}
} public Value get(Key key){
for(Node x = first;x!= null;x= x.next){
if(key.equals(x.key)){
return x.val;
}
}
return null; } public void delet(Key key){
for(Node x = first;x!= null;x= x.next){
if(key.equals(x.key)){
x.last.next = x.next;
return;
}
}
return;
} public void print(){
int i = 0;
if(first == null){
System.out.println(" ");
return;
}
for(Node x = first;x!= null;x= x.next){
i++;
System.out.println(x.key+" "+x.val );
} } }
public static void main(String[] args) {
ChainingHash<String, Integer> st = new ChainingHash<String, Integer>(517);
int N = args.length;
for (int i = 0;i < N; i++) {
String key = args[i];
st.put(key, i);
} // print keys
st.print();
} }
05-11 13:16