数据结构链表之符号表
符号表的介绍
- 之前章节介绍的顺序表和链表都是一个节点储存一个元素的表,但在日常生活中我们还有很多一次需要储存成对或多个值的情况,例如:
- 符号表最主要的目的将一对元素,用一个键和一个值将其联系起来,储存的值则是一个键和一个值共同组成的数据对,在查询元素时,我们只需要找到键即可查找到对应的元素
- 符号表的键具有唯一性
符号表的实现
- 可以用数组(Python中为列表)实现,也可以用链表实现,这里是链表,这里的节点实现和之前的链表实现有点不同,这里的节点有一个key、一个value还有一个next
- 有序符号表的实现,有序符号表指按照键的一定顺序对符号表进行排列,有序符号表的实现过程可以参照下面的图例:
在使用python代码实现符号表之前,看一下我们之前定义的链表,是下面这样的:
这里的head可以当做一个名称,它总是代表第一个结点,当没有首结点时,它为None,也没有next.
但本次我们将链表稍微修改一下,实现的链表是这样的:
这样子做是让代码写起来更加简洁易懂(可以省去很多需要单独对head结点进行的操作,实际上Java中的链表就是这样定义的)
主要用链表实现符号表的以下几个功能:
- size()获取符号表的大小
- show_items()以字典形式展示符号表中的元素
- put()将元素放入到符号表,需要考虑以键的顺序排列,重复键的value将会被替代
- delete()根据key来删除指定结点
- get_item()通过key获取对应结点的value
python代码实现
import operator
class Node:
def __init__(self, key, value):
self.key = key
self.value = value
self.next = None
class SymbolTable:
"""The head does not equal to the first element, but a none-value node"""
def __init__(self):
self.head = Node(None, None)
self.len = 0
def size(self):
"""Length of this symbol table"""
return self.len
def show_items(self):
"""Show items in a dict"""
items = {}
cur = self.head
while cur.next:
cur = cur.next
items[cur.key] = cur.value
return items
def put(self, _key, _value):
"""Put element into the symbol table"""
node = Node(_key, _value)
cur = self.head.next
pre = self.head
while cur and operator.gt(_key, cur.key):
pre = cur
cur = cur.next
# Key equals to _key, swap their values
if cur and _key == cur.key:
cur.value = _value
return
# _key < cur.key or got to the end
node.next = cur
pre.next = node
self.len += 1
def delete(self, _key):
"""Delete an element matched to the key"""
pre = self.head
cur = self.head.next
while cur:
if _key == cur.key:
pre.next = cur.next
self.len -= 1
return
pre = cur
cur = cur.next
else:
raise ValueError('SymbolTable.delete(x): x not in table')
def get_item(self, _key):
"""Get a value matched to the key"""
cur = self.head
while cur.next:
cur = cur.next
if _key == cur.key:
return cur.value
功能测试
if __name__ == '__main__':
ST = SymbolTable()
key1 = 'f'
key2 = 'g'
key3 = 'h'
key4 = 'e'
print(f"Put a into key[{key1}]", ST.put(key1, 1))
print(f"Put b into key[{key2}]", ST.put(key2, 2))
print(f"Put c into key[{key3}]", ST.put(key3, 3))
print(f"Put d into key[{key4}]", ST.put(key4, 4))
print(f"Show items:", ST.show_items())
key = 'g'
ST.delete(key)
print(f"Delete an element matched to key[{key}]", f"The items now is: {ST.show_items()}")
print(f"Size: ", ST.size())
key = 'f'
print(f"Get value by key[{key}]:", ST.get_item(key))
结果:
Put a into key[f] None
Put b into key[g] None
Put c into key[h] None
Put d into key[e] None
Show items: {'e': 4, 'f': 1, 'g': 2, 'h': 3}
Delete an element matched to key[g] The items now is: {'e': 4, 'f': 1, 'h': 3}
Size: 3
Get value by key[f]: 1