分离链接散列表

分离链接散列表的实现
做法:将散列到同一个值的所有元素保留到一个表中。

//分离链接散列表 separate chaining

//template<typename T>
struct ListNode;
//template<typename T>
typedef struct ListNode* Position;
typedef struct ListNode* List;


struct ListNode{
    int element;
    Position next;
};

struct HashTable{
    int table_size;
    List *the_lists;
};

//分离链接散列表 初始化例程
HashTable InitializeTable(int table_size){
    HashTable *H;
    H = new HashTable;
    //H = malloc(sizeof(struct HashTable));

    H->table_size = table_size;
    H->the_lists = new List[table_size];

    for (int i = 0; i != H->table_size; i++){
        H->the_lists[i] = new ListNode();
        //H->the_lists[i] = malloc(sizeof(struct ListNode));
        H->the_lists[i]->next = NULL;
    }

    return *H;
}

//Insert 例程  可重复
void Insert(int key, HashTable H){
    //Position pos, new_cell;
    List list = H.the_lists[(key / H.table_size)];

    ListNode* new_cell = new ListNode();
    new_cell->element = key;
    new_cell->next = list->next;
    list->next = new_cell;

}

//Find例程
Position Find(int key, HashTable H){
    List list = H.the_lists[(key / H.table_size)];
    while (list != NULL && list->element != key){
        list = list->next;
    }
    return list;
}

使用示例:


    HashTable H = InitializeTable(7);
    Insert(5, H);
    Insert(7, H);

    Position p=Find(5, H);
    if (p != NULL){
        cout << "find " << p->element << endl;
    }
    else{
        cout << "not find" << endl;
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值