首先看乙個面試題:
找到乙個字串中第一次出現一次的字元?
思路是:如果是a-z26個字元,可以設定大小為26的陣列,將每個字元出現的次數依次存放在陣列裡。如果是所有字元,將所有字元按照各自的asscii碼作為下標將出現的次數存放在陣列裡。
**如下:
對於這個題用的就是雜湊的思想,找到每個字元對應的位置。char findfirstchar( const
char *str)
;//所有字元
//int hashtable[26] = ;//記錄每次字元出現的次數,初始設定出現0次
char *s1 = ( char*)str;
//char *s1 =(unsigned char*)str;
while (*s1)
s1 = (char *)str;
//s1 = (unsigned char *)str;
while (*s1)
return -1;
}
雜湊表是通過雜湊函式使元素的儲存位置與它 的關鍵碼之間能夠建立一一對映的關係,在查詢時可以很快找到該元素。
雜湊函式hash(key)=key%m(m為記憶體單元的個數)。
雜湊衝突:
1.閉雜湊:當表中還有被裝滿,可以把key存放在表中的「下乙個「」空位置。即從發生衝突的位置開始,依次向後探測,直到找到空位置為止。
當雜湊表的載荷因子:填入表中的元素個數/雜湊表的長度結果在0.8以上時衝突的可能性越大。所以當載荷因子大於 0.8時就應該擴容。
2.二次探測:hi=(ho+i^2)%m,hi=(ho-i^2)%m,i=1,2,3…(m是表的大小)
插入:
使用雜湊函式找到待插入元素在雜湊表的位置,如果該位置沒有元素則直接插入新元素,如果該位置中有元素和待插入元素相同,則不用插入,如果該位置有元素但不是待插入元素即發生雜湊衝突,則可以使用線性探測和二次探測找到下乙個空位置。
**如下:
hash.h
hash.c#pragma once
typedef
int htdatatype;
enum status
;typedef
struct hashnode
hashnode;
typedef
struct hashtable阿
hashtable;
void htinit(hashtable *ht, size_t capacity);//雜湊表初始化
//成功:0,失敗-1
int htinsert(hashtable *ht, htdatatype key);//插入資料
htdatatype htfind(hashtable *ht, htdatatype key);//查詢
int htremove(hashtable *ht, htdatatype key);//刪除
void htprint(hashtable ht);//列印雜湊表
void htdestroy(hashtable *ht);//銷毀雜湊表
測試用例:#include
#include
#include
#include
#include"hash.h"
void testhashtable()
htprint(ht);//列印雜湊表;
htdestroy(&ht);
}int main()
int getprime(hashtable *ht)
; int index = 0;
while (index < _primesize)
index++;
}return _primelist[_primesize - 1];
}void htinit(hashtable *ht, size_t capacity)//雜湊表初始化
}int hashfunc(hashtable * ht, htdatatype key)
void checkcapacity(hashtable *ht)
free(ht->hash);
ht->hash = newht.hash;
ht->_size = newht._size;
ht->_capacity = newht._capacity;
}}int htinsert(hashtable *ht, htdatatype key)//插入資料
ht->hash[index]._key = key;
ht->_size++;
ht->hash[index]._status = exist;
return0;}
void htprint(hashtable ht)//列印雜湊表
printf("\n");
}htdatatype htfind(hashtable *ht, htdatatype key)//查詢
index++;
if (index == ht->_capacity)
index = 0;
}return -1;
}int htremove(hashtable *ht, htdatatype key)//刪除
else
return - 1;//該資料已經被刪除,無法再刪除
}index++;
if (index == ht->_capacity)
index = 0;
}return -1;//沒有找到該資料,刪除失敗
}void htdestroy(hashtable *ht)//銷毀雜湊表
實現鍊錶的初始化,按值查詢,插入,刪除
include include include define ok 1 define error 0 define true 1 define false 0 typedef char elemtype typedef struct node 結點型別定義 node,linklist void in...
鍊錶的初始化 插入 刪除 查詢等操作(詳細!)
鍊錶的初始化 插入 刪除 查詢等操作 詳細!最近在學習資料結構和演算法,為了提高對 的理解,把自己手寫的 分享出來,以下是 main.c list 0911 created by wangping on 2020 9 11.include include include define ok 1 de...
順序棧的初始化,建立,插入,查詢,刪除
順序棧的初始化,建立,插入,查詢,刪除。author wang yong date 2010.8.19 include include define max 100 定義最大棧容量 typedef int elemtype 定義棧型別 typedef struct seqstack 棧的初始化 se...