复习数据结构 哈希表

    科技2022-07-10  195

    哈希表hashtable(key,value) 就是把Key通过一个固定的算法函数既所谓的哈希函数转换成一个整型数字,然后就将该数字对数组长度进行取余,取余结果就当作数组的下标,将value存储在以该数字为下标的数组空间里。

    #include <iostream> using namespace std; enum Status {Active, Removed, Empty}; struct HashTable { int *key; //数据 int size; //元素个数 int remains; //剩余元素 Status *status; //状态 HashTable(int size) { key = new int[size]; this->size = this->remains = size; status = new Status[size]; for (int i = 0; i < size; i ++) status[i] = Empty; } int hash(int x, int p) { return x % p; } int findX(int x) { int pos = hash(x, size); int index = pos; while (status[pos] != Empty) { if (key[pos] == x && status[pos] == Active) return pos; pos = (pos + 1) % size; if (pos == index) break; } return -1; } bool isFull() { return remains == 0 ? true : false; } bool insertX(int x) { if (isFull()) return false; int pos = hash(x, size); while (status[pos] == Active) //一定有空位或删除位 pos = (pos + 1) % size; key[pos] = x; status[pos] = Active; remains --; return true; } bool removeX(int x) { int pos = findX(x); if (pos == -1) return false; status[pos] = Removed; remains ++; return true; } void printHT() { for (int i = 0; i < size; i ++) printf("M", i); cout << endl; for (int i = 0; i < size; i ++) if (status[i] == Active) printf("M", key[i]); else if (status[i] == Empty) printf(" -"); else printf(" X"); cout << endl; } }; int main() { HashTable ht(11); ht.printHT(); ht.insertX(5); ht.insertX(16); ht.insertX(10); ht.insertX(21); ht.insertX(33); ht.insertX(9); ht.insertX(20); ht.removeX(21); ht.printHT(); cout << ht.findX(21) << endl; cout << ht.findX(5) << endl; cout << ht.findX(20) << endl; int lalala; cin >> lalala; return 0; }
    Processed: 0.060, SQL: 8