Advertisement
Guest User

hashtable simple

a guest
Dec 15th, 2019
109
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.64 KB | None | 0 0
  1. #include <iostream>
  2. #include <string>
  3. #define SIZE 20
  4. using namespace std;
  5.  
  6. struct HashItems {
  7.     int key;
  8.     int value;
  9.     HashItems *next;
  10.     HashItems(int k, int val): key(k), value(val), next(NULL) {};
  11. };
  12.  
  13. struct HashTable {
  14.     HashItems *item;
  15. };
  16.  
  17. HashTable htable[SIZE];
  18.  
  19. int get_simple_hash(int key) {
  20.     return key % SIZE;
  21. }
  22.  
  23. void insert(int value) {
  24.     int hashkey = get_simple_hash(value);
  25.     HashTable ht = htable[hashkey];
  26.     HashItems *head = ht.item;
  27.     if(head == NULL) {
  28.         cout<<"No item at this key"<<endl;
  29.         HashItems *firstItem;
  30.         firstItem = new HashItems(hashkey, value);
  31.         head = firstItem;
  32.         ht.item = head;
  33.         htable[hashkey] = ht;
  34.     }
  35.     else {
  36.         cout<< "key already exists: avoid collision"<<endl;
  37.         HashItems *node = head;
  38.         while(node->next != NULL) {
  39.             node = node->next;
  40.         }
  41.         HashItems *nthitem;
  42.         nthitem = new HashItems(hashkey, value);
  43.         node->next = nthitem;
  44.         ht.item = head;
  45.         htable[hashkey] = ht;
  46.     }
  47. }
  48.  
  49. void find(int value) {
  50.     int hashkey = get_simple_hash(value);
  51.     HashTable ht = htable[hashkey];
  52.     HashItems *head = ht.item;
  53.  
  54.     if(head != NULL) {
  55.         while(head!=NULL) {
  56.             if(head->value == value) {
  57.                 cout<<"Found "<<value<<endl;
  58.                 return;
  59.             }
  60.             head = head->next;
  61.         }
  62.     }
  63.     else {
  64.         cout<<"not found" <<endl;
  65.     }
  66. }
  67.  
  68. int main() {
  69.     insert(12);
  70.     insert(90);
  71.     insert(77);    
  72.     insert(32);
  73.  
  74.     find(90);
  75.     find(32);
  76.     find(44);
  77.     return 0;
  78. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement