哦算法4上符号表的实现少了一个判断first是否为null的情况= =
拉链法散列表实现如下:
/**
* Created by eminem on 16-11-22.
*/
//拉链法散列表
public class sanLieBiao {
private int N;
//链表数量
private int M;
private SequentialSearchST<String, Integer>[] st;
public sanLieBiao() {
this(997);
}
public sanLieBiao(int M) {
this.M = M;
st = (SequentialSearchST<String, Integer>[]) new SequentialSearchST[M];
for (int i = 0; i < M; i++) {
st[i] = new SequentialSearchST();
}
}
private int hash(String key) {
return (key.hashCode() & 0x7fffffff) % M;
}
public Integer get(String key) {
return st[hash(key)].get(key);
}
public void put(String key, Integer val) {
st[hash(key)].put(key, val);
}
public Integer delete(String key){
return st[hash(key)].delete(key);
}
//此处还应该有一个迭代器
// public Iterable<String> keys(){
//
// }
}
class SequentialSearchST<String, Integer> {
private Node first;
private class Node {
String Key;
Integer val;
Node next;
public Node(String key, Integer val, Node next) {
this.Key = key;
this.val = val;
this.next = next;
}
}
public Integer get(String key) {
for (Node x = first; x != null; x = x.next) {
if (key.equals(x.Key)) {
return x.val;
}
}
System.out.println("get:Can't find the key"+"="+"\""+key+"\"");
return null;
}
public void put(String key, Integer val) {
if (first == null) {
first = new Node(key, val, first);
return;
} else {
for (Node x = first; x != null; x = x.next) {
if (key.equals(x.Key)) {
x.val = val;
return;
}
}
first = new Node(key, val, first);
}
}
public Integer delete (String key) {
//如果这条链表本身就是空的
if(first==null){
System.out.println("delete:Can't find the key"+"="+"\""+key+"\"");
return null;
}
Node x = first;
Node y = x;
//如果该条链表不是空的那就让这两个指针一前一后走到合适的位置
while (!key.equals(x.Key)) {
y = x;
x = x.next;
if(x==null){
System.out.println("delete:Can't find the key"+"="+"\""+key+"\"");
return null;
}
}
Integer fuck=x.val;
//处理不同位置的x
if(x==first){
first=null;
}else{
y.next=x.next;
}
return fuck;
}
}
public class Fucktest{
public static void main(String[] args) {
sanLieBiao sanlie=new sanLieBiao();
int num=1;
char i = 'a';
for (; i <'z'+1; i++,num++) {
sanlie.put(String.valueOf(i),num);
}
i='a';
for(int tmp=1;tmp<27;tmp++){
System.out.println(sanlie.get(String.valueOf(i++)));
}
}
}
md这个删除函数好难调啊。。