修改版hash
继续:
#include <iostream> using namespace std; struct hash_node { int data; hash_node *next; }; hash_node *Data[100] = {NULL}; int hash_fun(int key) { return key % 9; } void insert_data(int key) { int pos = hash_fun(key); hash_node *node = new hash_node(); node->data = key; node->next = NULL; hash_node *temp = Data[pos]; if (temp == NULL) { Data[pos] = node; } else { while (temp && temp->next) { temp = temp->next; } temp->next = node; } } bool find_data(int key) { int pos = hash_fun(key); hash_node *temp = Data[pos]; while(temp) { if (temp->data == key) { return true; } temp = temp->next; } return false; } bool delete_data(int key) { int pos = hash_fun(key); hash_node *temp1 = Data[pos]; if (temp1 && temp1->data == key) { Data[pos] = temp1->next; delete temp1; return true; } else { hash_node *temp2 = temp1->next; while (temp2) { if (temp2->data == key) { temp1->next = temp2->next; delete temp2; return true; } else { temp1 = temp2; temp2 = temp2->next; } } } return false; } void print() { for (int i = 0; i < 100; ++i) { if (Data[i]) { cout << i << " : "; cout << Data[i]->data << " "; hash_node *temp = Data[i]->next; while (temp != NULL) { cout << temp->data << " "; temp = temp->next; } cout << endl; } } } int main() { int a[10]={23,32,53,1,5,67,13,26,92,85}; for (int i = 0; i < 10; ++i) { insert_data(a[i]); } print(); //cout << find_data(23) << " " << find_data(100) <<endl; delete_data(23); print(); }