符号表是一种存储键值对的数据结构,支持两种操作:
插入(input),即将一组新的键值对存入到表中;
查找(get),即根据给定的键得到相应的值。
package searching; import java.util.ArrayList; import java.util.List; /** * 基于无序链表的顺序查找 * 符号表最主要的目的就是将一个键和一个值联系起来 * 符号表的实现使用了一个私有内部Node类来在链表中保存键和值 * get():顺序搜索链表查找给定的键(找到则返回相关联的值) * put():顺序搜索链表查找给定的键(找到,则更新相关联的值) * 否则他会用给定的键值对创建一个新的结点并将其插入到链表的头部。 */ public class SequentialSearchST<Key,Value> { private Node first;//链表首结点 private class Node{//私有内部Node类来在链表中保存键和值 Key key; Value val; Node next; public Node(Key key, Value val, Node next) { this.key = key; this.val = val; this.next = next; } } //查找给定的键,返回相关联的值 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 put(Key key,Value val){ 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 int size(){ int N=0; for(Node x=first;x!=null;x=x.next){ N++; } return N; } //删除键key及对应的值 public void delete(Key key){ for(Node x=first;x!=null;x=x.next){ if (key.equals(x.next.key)) { x.next=x.next.next; } } } //键key在表中是否有对应的值 public boolean contains(Key key){ for(Node x=first;x!=null;x=x.next){ if (key.equals(x.key)) { return true; } } return false; } public Iterable<Key> keys(){ List<Key> keys=new ArrayList<>(); for(Node x=first;x!=null;x=x.next){ keys.add(x.key); } return keys; } }
从输入中得到一列字符串并记录每个字符串的出现次数,然后遍历所有键并找出出现频率最高的键
package searching; import java.util.Scanner; public class TestSequentialSearchST { public static void main(String[] args) { // TODO Auto-generated method stub int minLen=2;//最小键长 Scanner scanner=new Scanner(System.in); SequentialSearchST<String, Integer> st=new SequentialSearchST<>(); while(true){ String s=scanner.nextLine(); if (s.equals("eof")) { break; } if (s.length()<minLen) {//忽略较短单词 continue; } if (!st.contains(s)) { st.put(s, 1); }else { st.put(s, st.get(s)+1); } } String max=" "; st.put(max, 0); for(String i:st.keys()){ if (st.get(i)>st.get(max)) { max=i; } } System.out.println(max+" "+st.get(max)); } }