有序符号表
在符号表的基础上,对键的值进行排序,实现有序符号表
添加元素分析
1.首先,使key继承comparable接口
2.通过链表的遍历,比较键的大小,知道该节点的键大于待插入键,则停止
3.关键在于记录大于待插入键的上一个结点,来便于元素的插入
4.当键相同时实现替换
public void put(Key key,Value value){
Node curr = head.next;
Node pre = null;
while (curr != null && key.compareTo(curr.key) > 0) {
pre = curr;
curr = curr.next;
}
if (curr != null && key.compareTo(curr.key) == 0) {
curr.value = value;
return;
}
Node newNode = new Node(key, value, null);
pre.next = newNode;
N++;
}
测试
public class orderSymbolTest {
public static void main(String[] args) {
OrderSymbolTable<Integer, String> orderSymbolTable = new OrderSymbolTable<>();
orderSymbolTable.put(1,"1");
orderSymbolTable.put(2,"2");
orderSymbolTable.put(4,"4");
orderSymbolTable.put(3,"3");
}
}
|