文章目录
- 链表
- python实现
- 双向链表
- 复杂度分析
- 哈希表(散列表)
- python实现哈希表
- 哈希表的应用
链表
python实现
class Node:def __init__(self, item):self.item = itemself.next = Nonedef head_create_linklist(li):head = Node(li[0])for element in li[1:]:node = Node(element)node.next = headhead = nodereturn headdef tail_create_linklist(li):head = Node(li[0])tail = headfor element in li[1:]:node = Node(element)tail.next = nodetail = nodereturn headdef print_linklist(lk):while lk:print(lk.item, end=',')lk = lk.nextprint()a = head_create_linklist([1, 2, 3, 4, 5, 6, 7, 8])
b = tail_create_linklist([1, 2, 3, 4, 5, 6, 7, 8])
print_linklist(a)
print_linklist(b)
双向链表
复杂度分析
哈希表(散列表)
python实现哈希表
class LinkList:class Node:def __init__(self, item=None):self.item = itemself.next = Noneclass LinkListIterator:def __init__(self, node):self.node = nodedef __next__(self):if self.node:cur_node = self.nodeself.node = cur_node.nextreturn cur_node.itemelse:raise StopIterationdef __iter__(self):return selfdef __init__(self, iterable=None):self.head = Noneself.tail = Noneif iterable:self.extend(iterable)def append(self, obj):s = LinkList.Node(obj)if not self.head:self.head = sself.tail = selse:self.tail.next = sself.tail = sdef extend(self, iterable):for obj in iterable:self.append(obj)def find(self, obj):for n in self:if n == obj:return Trueelse:return Falsedef __iter__(self):return self.LinkListIterator(self.head)def __repr__(self):return "<<" + ", ".join(map(str, self)) + ">>"# 类似于集合的结构
class HashTable:def __init__(self, size=101):self.size = sizeself.T = [LinkList() for i in range(self.size)]def h(self, k):return k % self.sizedef insert(self, k):i = self.h(k)if self.find(k):print("Duplicated Insert.")else:self.T[i].append(k)def find(self, k):i = self.h(k)return self.T[i].find(k)ht = HashTable()ht.insert(0)
ht.insert(1)
ht.insert(3)
ht.insert(102)
ht.insert(508)
ht.insert(19)
ht.insert(56)
ht.insert(96)print(",".join(map(str, ht.T)))
print(ht.find(203))
哈希表的应用
若有错误与不足请指出,关注DPT一起进步吧!!!