Zipper method: In a linear list, this linear list address uniquely identified by its hash synonyms of all storage. Applicable to the case of frequent insert and delete operations.
Code and comments:
. 1 #include " the iostream " 2 #include " Vector " . 3 #include <time.h> . 4 the using namespace STD; . 5 . 6 // fastener method . 7 . 8 struct ListNode // node is composed of a single linked list, a hash table a set of pointers, the array index is assigned to find out the key value . 9 { 10 int Val; . 11 struct ListNode * next; 12 is ListNode ( int X): Val (X), next (NULL) {} 13 is }; 14 15 int hash_func (int key, int table_len) { // New Method for the key value is, the array length of the hash taken over 16 return key% table_len; . 17 } 18 is . 19 void INSERT (ListNode hash_table * [], ListNode Node *, int table_len) { // insertion method is the first interpolation method 20 is int HASH_KEY = hash_func (node-> Val, table_len); 21 is node-> Next = hash_table [HASH_KEY]; 22 is hash_table [HASH_KEY] = Node; 23 is } 24 25 BOOL Search (ListNode hash_table * [], int Val, inttable_len) { // method to find the insertion idea is almost the same 26 is int HASH_KEY hash_func = (Val, table_len); // only node is inserted, only to find to find the value 27 ListNode head * = hash_table [ HASH_KEY]; 28 the while (head) { 29 IF (head-> == Val Val) 30 { 31 is return to true ; 32 } 33 is head = head-> Next; 34 is } 35 return to false ; 36 } 37 [ 38 is // test: 39 int main () { 40 const int TABLE_LEN = . 11 ; // taken to be a prime number, will be relatively small conflicts 41 is ListNode * hash_table [TABLE_LEN] {= 0 }; // pointer array 42 is Vector <ListNode *> hash_node_vec; 43 is int Test [ 8 ] = { 0 }; 44 is srand (Time (NULL)); // randomly generated 8 hours to the number 10 of 45 for ( int I = 0 ; I < 8 ; I ++ ) { 46 is Test [I] = RAND () % 10; 47 } 48 for (int i = 0; i < 8; i++) { 49 hash_node_vec.push_back(new ListNode(test[i])); 50 } 51 for (int i = 0; i < hash_node_vec.size(); i++) { 52 insert(hash_table, hash_node_vec[i], TABLE_LEN); 53 } 54 printf("Hash table:\n"); 55 for (int i = 0; i < TABLE_LEN; i++) { 56 printf("[%d]:", i); 57 ListNode* head = hash_table[i]; 58 while (head) { 59 printf("->%d", head->val); 60 head = head->next; 61 } 62 printf("\n"); 63 } 64 printf("\n"); 65 printf("Test search:\n"); 66 for (int i = 0; i < 10; i++) { 67 if (search(hash_table, i, TABLE_LEN)) { 68 printf("%d is in the hash table.\n", i); 69 } 70 else { 71 printf("%d is not in the hash table.\n", i); 72 } 73 } 74 system("pause"); 75 return 0; 76 }
Step by step to move forward, there is always rewarding, keep quiet. 2020-03-20