/**
* 键值有序的符号表
* @param <Key>
* @param <Value>
*/
public class OrderSymbolTable<Key extends Comparable,Value> {
private class Node{
public Key key;
public Value value;
public Node next;
public Node(Key key, Value value, Node next) {
this.key = key;
this.value = value;
this.next = next;
}
}
private Node head;
private int size;
public OrderSymbolTable() {
this.head = new Node(null,null, null);
this.size = 0;
}
//根据键值获取相应的值
public Value get(Key key){
Node pNode = head;
while (pNode.next!=null){
pNode = pNode.next;
if (pNode.key.equals(key)){
return pNode.value;
}
}
return null;
}
//向符号表中插入一个键值对,在这里是有序符号表
public void put(Key key,Value value){
//在这里需要遍历有序符号表,每一次对比key值,当key的大小在两个元素中间时,则插入,如果key相等,则替换
Node pNode = head;
Node pre = head;
Node newNode = new Node(key,value,null);
while (pNode.next!=null){
pre = pNode;
pNode = pNode.next;
if (key.compareTo(pNode.key)>0){
continue;
} else if (key.compareTo(pNode.key)==0){
pNode.value = value;
return;
} else {
newNode.next = pNode;
pre.next = newNode;
size++;
return;
}
}
pNode.next = newNode;
size++;
}
//删除键为key的键值对
public void delete(Key key){
Node pNode = head;
Node pre = head;
while (pNode.next!=null){
pre = pNode;
pNode = pNode.next;
if (pNode.key.equals(key)){
pre.next = pNode.next;
size--;
return;
}
}
}
//获取符号表的大小
public int getSize(){
return size;
}
//测试
public static void main(String[] args) {
OrderSymbolTable<Integer,String> symbolTable = new OrderSymbolTable();
symbolTable.put(1,"xiongda");
symbolTable.put(2,"xionger");
symbolTable.put(3,"zhangsan");
System.out.println(symbolTable.size);
symbolTable.put(1,"lisi");
System.out.println(symbolTable.size);
String value = symbolTable.get(2);
System.out.println(value);
symbolTable.delete(2);
System.out.println(symbolTable.size);
}
}
数据结构之链表--有序符号表
最新推荐文章于 2024-01-01 20:47:49 发布