开地址哈希表,结构如下,采用双散列哈希函数,但事先要制定好哈希表的大小:
struct ohtbale{
positions : i32, //需要指定的哈希表大小(槽位个数)
size : i32,
table : Vec<Option<i32>>,
}
impl ohtbale{
//双散列哈希函数, k待插入的值,i当前探索位置, m槽位个数
// h(k,i) = (h1(k) + i*h2(k)) mod m
// h1(k) = k mod m; h2(k) = 1 + (k mod (m-2))
fn hashfunc(&self,data:i32,iexplore:i32) -> i32{
return (data % self.positions + iexplore*(1 + data % (self.positions - 2))) % self.positions;
}
fn lookup(&self,data:i32) -> bool{
for i in 0..self.positions{
let position = self.hashfunc(data,i);
if let Some(value) = self.table[position as usize]{
if value == data{
return true;
}
}
else{
return false;
}
}
return false;
}
pub fn new(positions:i32) -> Self{
let mut tt : Vec<Option<i32>> = Vec::new();
for _ in 0..positions{
tt.push(None);
}
Self{
positions: positions,
size : 0,
table : tt,
}
}
pub fn insert(&mut self,data:i32){
//达到最大容量无法插入新元素
if self.size == self.positions{
return;
}
//元素已经,则存在不插入
if self.lookup(data) {
return;
}
for i in 0..self.positions{
let position = self.hashfunc(data,i);
if let Some(_) = self.table[position as usize]{
//如果有数值跳过找下一个位置
}else{
self.table[position as usize] = Some(data);
self.size += 1;
return;
}
}
}
pub fn remove(&mut self,data:i32){
for i in 0..self.positions{
let position = self.hashfunc(data,i);
if let Some(value) = self.table[position as usize]{
if value == data{
self.table[position as usize] = None;
self.size -= 1;
}
}
else{
return;
}
}
return;
}
}
pub fn run(){
let mut myhash = ohtbale::new(10);
myhash.insert(3);
myhash.insert(77);
myhash.insert(250);
myhash.insert(77);
myhash.remove(8);
println!("{:?}",myhash.table);
}
结果如下: