Chain Hash Table: 插入函数

Chain Hash Table: Insert function

我一直在尝试为我的 MyChainHashTable class.

编写一个 insert(self, key) 方法

应该使用单独的链接来处理冲突解决。如果键不在散列 table 中,则应将键插入散列链表的末尾,并 return 插入散列键。如果密钥已经在散列 table 中,那么它应该 return -1.

这是我的 class:

class MyChainHashTable:

    def __init__(self, capacity):
        self.capacity = capacity
        self.slots = [ ]
        for i in range(self.capacity):
            self.slots.append([])

    def __str__(self):
        info = ""
        for items in self.slots:
            info += str(items)
        return info

    def __len__(self):
        count = 0
        for i in self.slots:
            count += len(i)
        return count

    def hash_function(self, key):
        i = key % self.capacity
        return i

我试过这个:

    def insert(self, key):
        self.slots[self.hash_function(key)].append(key)

但我不知道如何解决冲突或如何 return -1

测试是:

x = MyChainHashTable(2)
print("Add 3, return:", x.insert(3))
print("Add 3, return:", x.insert(3))
print("Hashtable:", x)

结果应该是:

Add 3, return: 1
Add 3, return: -1
Hashtable: [][3]

如你所愿:

    def insert(self, key):
        slot = self.hash_function(key)
        if key in self.slots[slot]:
            return -1
        else:
            self.slots[slot].append(key)
            return slot