算法3.1 无序链表中的顺序查找

实现:符号表的实现使用私有内部类Node保存键值对,get()会顺序地搜索链表查找给定的值,put()的实现会顺序搜索链表查找给定的键,找到则更新值,否则创建新结点并插在链表开头.

  1. public class SequentialSearchST<Key, Value>{
  2. int size = 0;
  3. private Node first;
  4. private class Node{
  5. Key key;
  6. Value value;
  7. Node next;
  8. public Node(Key key, Value value, Node next){
  9. this.key = key;
  10. this.value = value;
  11. this.next = next;
  12. }
  13. }
  14. private Value get(Key key){
  15. for (Node x = first; x != null; x = x.next){
  16. if (key.equals(x.key))
  17. return x.value;//找到键值,并返回
  18. }
  19. return null;//无键值
  20. }
  21. private void put(Key key, Value value){
  22. for (Node x = first; x != null; x = x.next){
  23. if (key.equals(x.key)) {
  24. x.value = value;//找到键值,并更新
  25. return;
  26. }
  27. }
  28. first = new Node(key, value, first);//无键值,则在头结点插入新键值
  29. size++;
  30. }
  31. private int size(){ return size;}
  32. private void delete(Key key){
  33. //延时删除先将键值置空put(key, null),之后一并删除空值结点
  34. //即时删除
  35. for (Node x = first; x != null; x = x.next){
  36. if (x.next.key.equals(key))
  37. x.next = x.next.next;
  38. }
  39. }
  40. }

算法分析

  • 查找在最坏情况下序O(N),插入N个不同键需要~N²/2次比较(1+2+…+N)
  • 基于链表实现符号表和顺序查找都是非常低效的