你没有用拉链法解决地址冲突,修改一下上面的代码
时间: 2024-03-26 10:39:35 浏览: 49
好的,根据您的要求,我修改了一下拉链法解决地址冲突的代码,如下所示:
```
#define SIZE 100 // 哈希表大小
struct Node {
int key;
int value;
Node* next;
Node(int k, int v) : key(k), value(v), next(nullptr) {}
};
class HashTable {
private:
vector<Node*> table;
int hash(int key) {
return key % SIZE;
}
public:
HashTable() {
table.resize(SIZE, nullptr);
}
void put(int key, int value) {
int h = hash(key);
if (!table[h]) {
table[h] = new Node(key, value);
} else {
Node* p = table[h];
while (p) {
if (p->key == key) {
p->value = value;
return;
}
if (!p->next) break;
p = p->next;
}
p->next = new Node(key, value);
}
}
int get(int key) {
int h = hash(key);
Node* p = table[h];
while (p) {
if (p->key == key) {
return p->value;
}
p = p->next;
}
return -1;
}
void remove(int key) {
int h = hash(key);
Node* p = table[h];
if (!p) return;
if (p->key == key) {
table[h] = p->next;
delete p;
return;
}
while (p->next) {
if (p->next->key == key) {
Node* t = p->next;
p->next = t->next;
delete t;
return;
}
p = p->next;
}
}
};
```
以上是基于拉链法解决地址冲突的哈希表实现,我希望这个修改可以满足您的要求。
阅读全文
相关推荐
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231044955.png)
![-](https://img-home.csdnimg.cn/images/20241231044955.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231044833.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![pptx](https://img-home.csdnimg.cn/images/20241231044947.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)