雜湊桶的各操作總結 拉鍊法

2021-08-27 08:32:20 字數 2255 閱讀 7452

0.定義結構

//雜湊表中結點的型別(拉鍊法)

typedef

struct hashnode

hashnode;

//雜湊表的型別

typedef

struct hashtablebucket

htb;

1.介面宣告
//初始化

void htbinit(htb* htb, size_t len);

//銷毀雜湊表

void htbdestory(htb* htb);

//向雜湊表中插入乙個元素

int htbinsert(htb* htb, htbkeytype key, htbvaluetype value);

//刪除雜湊表中的乙個元素

int htbremove(htb* htb, htbkeytype key);

//在雜湊表中查詢乙個元素

hashnode* htbfind(htb* htb, htbkeytype key);

//雜湊表的大小

int htbsize(htb* htb);

//雜湊表是否為空

int htbempty(htb* htb);

2.函式實現
#include"hashtablebucket.h"

//初始化

void htbinit(htb* htb, size_t len)

htb->_table = table;

htb->_size = 0;

htb->_len = htb_len;

//將雜湊表中的所有指標初始化為空,否則會對野指標操作

memset(htb->_table, null, sizeof(hashnode*)*(htb->_len));

}//銷毀雜湊表

void htbdestory(htb* htb)

htb->_table[i] = null;

}//2.釋放雜湊表(動態開闢的陣列)

free(htb->_table);

htb->_table = null;

htb->_size = 0;

htb->_len = 0;

}//雜湊函式,計算雜湊位址(字串,模留餘數法)

static

int htbfunc(htbkeytype key, int len)

return

count%len;

}//雜湊函式,計算雜湊位址(整數)

//static int htbfunc(htbkeytype key, int len)

////建立雜湊結點

hashnode* buyhashnode(htbkeytype key, htbvaluetype value)

return node;

}//檢查負載因子是否達到1,如果達到1,則需要擴容,否則查詢效率會變慢

void checkhtbcapacity(htb* htb)

htb->_table[i] = null;

}//釋放舊表

free(htb->_table);

htb->_table = newhtb._table;

htb->_size = newhtb._size;

htb->_len = newhtb._len;

}}//向雜湊表中插入乙個元素

int htbinsert(htb* htb, htbkeytype key, htbvaluetype value)

//刪除雜湊表中的乙個元素

int htbremove(htb* htb, htbkeytype key)

if (cur->_key == key)

prev = cur;

cur = cur->_next;

}return0;}

//在雜湊表中查詢乙個元素

hashnode* htbfind(htb* htb, htbkeytype key)

cur = cur->_next;

}return null;

}//列印雜湊表(方便測試)

void printhtb(htb* htb)

printf("(count=%d)->over\n", count);

}}//雜湊表的大小

int htbsize(htb* htb)

//雜湊表是否為空

int htbempty(htb* htb)

雜湊拉鍊法(雜湊桶)

昨天寫了雜湊的開放定址法的部落格,今天我們要說的是拉鍊法,還有乙個名字叫雜湊桶。雜湊桶要做的就是,之前我們用的開放定址法,通過將資料對映到陣列中來實現雜湊。這裡每個陣列的位置只能存放乙個資料,如果衝突的話會繼續往下找找到空的位置然後放進去,但是其實大家都能感覺出來上乙個 很簡單,也很扯,感覺實現起來...

雜湊表(閉雜湊 拉鍊法 雜湊桶)

雜湊表,也稱雜湊表,是一種通過key值來直接訪問在記憶體中的儲存的資料結構。它通過乙個關鍵值的函式 被稱為雜湊函式 將所需的資料對映到表中的位置來訪問資料。關於雜湊表,主要為以下幾個方面 一 雜湊表的幾種方法 1 直接定址法 取關鍵字key的某個線性函式為雜湊位址,如hash key key 或 h...

雜湊表的基本操作 拉鍊法

hashtablebucket.h pragma once include include include include include typedef char htbkeytype typedef char htbvaluetype typedef char htbkeytype typede...