Advertisement
lordasif

Hashing

Jul 16th, 2019
107
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.29 KB | None | 0 0
  1. #include<iostream>
  2. #include<cstdlib>
  3. #include<stdio.h>
  4.  
  5. using namespace std;
  6.  
  7. int SIZE;
  8. struct Node
  9. {
  10. int val;
  11. Node * next;
  12. };
  13.  
  14. struct LinkedList
  15. {
  16. private:
  17. Node ** hashTable;
  18. public:
  19. void init(int s)
  20. {
  21. SIZE = s;
  22. hashTable = (Node**)calloc(SIZE,sizeof(Node*));
  23. }
  24.  
  25. int hashFunc(int key)
  26. {
  27. return key%SIZE;
  28. }
  29.  
  30. void insertValue(int v)
  31. {
  32. Node * newnode = new Node;
  33. newnode->val = v;
  34. newnode->next = NULL;
  35.  
  36. int index = hashFunc(v);
  37. if(hashTable[index] == NULL)
  38. {
  39. hashTable[index]=(Node*)malloc(sizeof(Node*));
  40. hashTable[index]=newnode;
  41. }
  42. else
  43. {
  44. Node* temp = new Node;
  45. temp = hashTable[index];
  46. newnode->next=temp;
  47. hashTable[index]=newnode;
  48. }
  49. }
  50. int searchValue(int v)
  51. {
  52. int index = hashFunc(v);
  53. if(hashTable[index]==NULL)
  54. {
  55. cout<<"Index is completely empty thus "<< v << " is not found"<< endl;
  56. }
  57. else
  58. {
  59. Node * temp = new Node;
  60. temp->val = v;
  61. temp = hashTable[index];
  62. int j = 0;
  63. while(temp != NULL)
  64. {
  65. if (temp->val == v)
  66. {
  67. cout<< v << " is found at "<< index <<" , " << j << endl;
  68. break;
  69. }
  70. j++;
  71. temp = temp ->next;
  72.  
  73. }
  74. if(temp == NULL)
  75. {
  76. cout<< v << " is not found" << endl;
  77. }
  78. }
  79. }
  80.  
  81. void display()
  82. {
  83. for(int i=0;i<SIZE;i++)
  84. {
  85. cout<<i<<"-->";
  86. if(hashTable[i] != NULL)
  87. {
  88. Node* temp=new Node;
  89. temp=hashTable[i];
  90. while(temp != NULL)
  91. {
  92. cout<<temp->val<<"-->";
  93. temp=temp->next;
  94. }
  95. }
  96. cout<<"\n";
  97. }
  98.  
  99. }
  100. };
  101.  
  102. int main()
  103. {
  104. LinkedList l1;
  105.  
  106. l1.init(10);
  107.  
  108. l1.insertValue(22);
  109. l1.insertValue(32);
  110. l1.insertValue(21);
  111. l1.insertValue(25);
  112. l1.insertValue(27);
  113.  
  114. l1.display();
  115.  
  116. l1.searchValue(32);
  117. l1.searchValue(2);
  118. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement