前言:
今天学习了一种新的抽象数据结构的API——符号表,它其实与一些编程语言中的字典dictionary很像,也是每一个元素都有key和value,可以根据key来寻找value。下面就来看看这种数据结构的详细内容和基本操作。
符号表:
先来看看符号表有什么用,比如我们生活中的字典,就是根据汉字来寻找释义,这里key就是汉字,value就是它的释义。还有很多很多应用:
来看看符号表的实现:
符号表有两种实现方式,一种是无序链表实现,另一种是有序数组实现。这里我使用的是无需链表实现。
基本操作:
Put操作:
Put操作是将元素加入到符号表中,如果Put的元素的key值在链表中已经存在,则将其覆盖,若不存在,则在链表末尾加入该元素。
Get操作:
Get操作是用key值在符号表中找到对应元素的value值,若找不到,则返回NULL。
Delete操作:
Delete操作是根据要删除元素的key值找到符号表中对应的元素并删除。
contains操作:
根据所给key值检查符号表中是否有要找的元素。
isEmpty操作:
检查符号表是否为空。
size()操作:
返回符号表的大小。
来看看c++ 代码:
template<class Tkey, class Tvalue>
class node{
public:
Tkey key;
Tvalue value;
node *next;
node(Tkey kk, Tvalue vv, node *nn = NULL){
key = kk;
value = vv;
next = nn;
}
};
template<class Tkey, class Tvalue>
class ST{
private:
node<Tkey, Tvalue> *head, *tail;
int length;
public:
ST(){
head = tail = NULL;
}
void Put(Tkey key, Tvalue value){
node<Tkey, Tvalue> *p;
if(head == NULL){
p = head;
p = new node<Tkey, Tvalue>(key, value);
head = tail;
head -> next = NULL;
length = length + 1;
}
else{
while(p != NULL){
if(p -> key == key){
p -> value = value;
return;
}
p = p -> next;
}
p = new node<Tkey, Tvalue>(key, value);
tail -> next = p;
tail = p;
tail -> next = NULL;
length = length + 1;
}
}
Tvalue Get(Tkey kkey){
Tvalue result;
node<Tkey, Tvalue> *p;
while(p != NULL){
if(p -> key == kkey){
result = p -> value;
return result;
}
p = p -> next;
}
return NULL;
}
void Delete(Tkey kkey){
Put(kkey, NULL);
}
bool contains(Tkey kkey){
return get(kkey) != NULL;
}
bool isEmpty(){
return length == 0;
}
int size(){
return length;
}
};
总结:
符号表中操作一般先要查找,查找的时候需要从链表头进行查找,所以插入和查找的平均时间复杂度均为O(n)。
最后强烈推荐Coursera上普林斯顿大学的算法课点击打开链接
以上内容纯属个人学习总结,不代表任何团体或单位。若有理解不到之处请见谅!