Advertisement
Guest User

Untitled

a guest
Jul 19th, 2019
83
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.30 KB | None | 0 0
  1. #include <iostream>
  2. using namespace std;
  3.  
  4. struct Node{
  5. int data;
  6. struct Node *next;
  7. };
  8.  
  9. int hash_(int key)
  10. {
  11. return key%10;
  12. }
  13.  
  14. void myinsert(struct Node **H,int ele){
  15. struct Node *p = *H;
  16. struct Node *t = new Node;
  17. t->data = ele;
  18. t->next = NULL;
  19. if(*H==NULL){ // Important to compare index address(*H) rather than p with NULL
  20. *H=t;
  21. }else{
  22. while(p->next!=NULL){
  23. p=p->next;
  24. }
  25. p->next = t;
  26. }
  27. }
  28.  
  29. void insert(struct Node *HT[], int ele){
  30. int index=hash_(ele);
  31. myinsert(&HT[index],ele);
  32. }
  33.  
  34.  
  35. void print_at_index(struct Node *HT[],int index){
  36. struct Node *p= HT[index];
  37. if(p==NULL){
  38. cout << "No elements here!";
  39. return;
  40. }
  41. while(p!=NULL){
  42. cout << p->data << " ";
  43. p=p->next;
  44. }
  45. cout << endl;
  46. }
  47.  
  48.  
  49. void print_all(struct Node *HT[]){
  50. for(int i=0;i<10;i++){
  51. struct Node *p= HT[i];
  52. if(p==NULL){
  53. cout << i << " -> NULL" << endl;
  54. }else{
  55. cout << i << " -> ";
  56. while(p!=NULL){
  57. cout << p->data << " -> ";
  58. p=p->next;
  59. }
  60. cout << "NULL";
  61. cout << endl;
  62. }
  63. }
  64. }
  65.  
  66. void del(struct Node * HT[],int key){
  67. int index = hash_(key);
  68. struct Node *p = HT[index], *q=NULL;
  69. if(p->next==NULL){ // Only one node is present
  70. HT[index] = NULL;
  71. delete p;
  72. }else if(key == p->data && p->next!=NULL){ // If first node has the key
  73. HT[index] = p->next;
  74. delete p;
  75. }else{
  76. while(p->data != key){ // Search for key, else return not found
  77. q=p;
  78. p=p->next;
  79. if(p==NULL and q->data!=key){
  80. cout << key << " not found!" << endl;
  81. return;
  82. }
  83. }
  84. q->next = p->next;
  85. delete p;
  86. }
  87. }
  88.  
  89. int main(){
  90. struct Node *HT[10];
  91.  
  92. for(int i=0;i<10;i++){
  93. HT[i]=NULL;
  94. }
  95.  
  96. insert(HT,12);
  97. insert(HT,22);
  98.  
  99. print_at_index(HT,2); // To print all keys at a particular index
  100. cout << endl;
  101. //print_all(HT); // To print all the indices in the form of a table
  102.  
  103. del(HT,12); // Delete key-12
  104.  
  105. print_all(HT);
  106. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement