1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135
|
#include <cstring> #include <math.h> using namespace std;
#define HTL 100 template <class > int length( &arr) { return sizeof(arr)/ sizeof(arr[0]); } int hashTable[HTL]={-1}; int key[9]={1,4,9,10,13,23,34,42,50}; bool isprime(int num) { for(int i=2;i<sqrt(num);i++) { if(num%i==0) return false; } return true; } int maxprime() { for(int i=HTL-1;i>=2;i--) { if(isprime(i)) return i; } } bool fullT() { bool flag = true; for(int i=0;i<maxprime();i++) { if(hashTable[i]==-1) { flag = false; break; } } return flag; } int hashFun(int key) { if(key<=0) return -1; int address = key%maxprime(); return address; } int solve_conflict(int address,int increment=1) { if(fullT()) { return -1; } address = hashFun(address+increment); if(hashTable[address]==-1) return address; else return solve_conflict(address,increment); } bool inithashTable() { int increment = 1; int address=0; for(int i=0;i < length(key);i++) { address = hashFun(key[i]); if(hashTable[address] == -1) hashTable[address] = key[i]; else { address = solve_conflict(address,increment); if(fullT()) { cout<<"表已满,关键字:"<<key[i]<<"无法存入"<<endl; return false; } hashTable[address] = key[i]; } } return true; } void print_key() { for(int i=0;i<length(key);i++) cout<<key[i]<<" "; cout<<endl; } void print_hashT() { for(int i=0;i<length(hashTable);i++) cout<<hashTable[i]<<" "; cout<<endl; }
bool add_hashE(int key) { if(key<=0) return false; int increment = 1; int address=0;
address = hashFun(key);
if(hashTable[address] == -1) hashTable[address] = key; else { address = solve_conflict(address, increment); if(fullT()) { cout<<"表已满,关键字:"<<key<<"无法存入"<<endl; return false; } hashTable[address] = key; } return true; } int main() { memset(hashTable,-1, sizeof(hashTable)); print_key(); cout<<"hash前:"<<endl; print_hashT(); inithashTable(); cout<<"hash后:"<<endl; print_hashT(); for(int i=10;i<120;i++) add_hashE(i); print_hashT(); return 0; }
|
近期评论