算法3.1 无序链表中的顺序查找
实现:符号表的实现使用私有内部类Node保存键值对,get()会顺序地搜索链表查找给定的值,put()的实现会顺序搜索链表查找给定的键,找到则更新值,否则创建新结点并插在链表开头.
public class SequentialSearchST<Key, Value>{
int size = 0;
private Node first;
private class Node{
Key key;
Value value;
Node next;
public Node(Key key, Value value, Node next){
this.key = key;
this.value = value;
this.next = next;
}
}
private Value get(Key key){
for (Node x = first; x != null; x = x.next){
if (key.equals(x.key))
return x.value;//找到键值,并返回
}
return null;//无键值
}
private void put(Key key, Value value){
for (Node x = first; x != null; x = x.next){
if (key.equals(x.key)) {
x.value = value;//找到键值,并更新
return;
}
}
first = new Node(key, value, first);//无键值,则在头结点插入新键值
size++;
}
private int size(){ return size;}
private void delete(Key key){
//延时删除先将键值置空put(key, null),之后一并删除空值结点
//即时删除
for (Node x = first; x != null; x = x.next){
if (x.next.key.equals(key))
x.next = x.next.next;
}
}
}
算法分析
- 查找在最坏情况下序O(N),插入N个不同键需要~N²/2次比较(1+2+…+N)
- 基于链表实现符号表和顺序查找都是非常低效的