fork download
  1. #include <iostream>
  2. using namespace std;
  3.  
  4. const int TABLE_SIZE = 10;
  5.  
  6. bool insert(int key, int value, int keys[], int values[], int state[]) {
  7. int index = key % TABLE_SIZE;
  8. for (int i = 0; i < TABLE_SIZE; i++) {
  9. int probe = (index + i) % TABLE_SIZE;
  10. if (state[probe] == 0 || state[probe] == 2) {
  11. keys[probe] = key;
  12. values[probe] = value;
  13. state[probe] = 1;
  14. return true;
  15. }
  16. }
  17. return false;
  18. }
  19.  
  20. int search(int key, int keys[], int values[], int state[]) {
  21. int index = key % TABLE_SIZE;
  22. for (int i = 0; i < TABLE_SIZE; i++) {
  23. int probe = (index + i) % TABLE_SIZE;
  24. if (state[probe] == 0) return -1;
  25. if (state[probe] == 1 && keys[probe] == key) return values[probe];
  26. }
  27. return -1;
  28. }
  29.  
  30. bool remove(int key, int keys[], int values[], int state[]) {
  31. int index = key % TABLE_SIZE;
  32. for (int i = 0; i < TABLE_SIZE; i++) {
  33. int probe = (index + i) % TABLE_SIZE;
  34. if (state[probe] == 0) return false;
  35. if (state[probe] == 1 && keys[probe] == key) {
  36. keys[probe] = -1;
  37. values[probe] = -1;
  38. state[probe] = 2;
  39. return true;
  40. }
  41. }
  42. return false;
  43. }
  44.  
  45. int main() {
  46. int keys[TABLE_SIZE];
  47. int values[TABLE_SIZE];
  48. int state[TABLE_SIZE];
  49.  
  50. for (int i = 0; i < TABLE_SIZE; i++) {
  51. keys[i] = -1;
  52. values[i] = -1;
  53. state[i] = 0;
  54. }
  55.  
  56. insert(1, 100, keys, values, state);
  57. insert(11, 200, keys, values, state);
  58. insert(21, 300, keys, values, state);
  59.  
  60. cout << "Keys: ";
  61. for (int i = 0; i < TABLE_SIZE; i++) cout << keys[i] << " ";
  62. cout << "\nValues: ";
  63. for (int i = 0; i < TABLE_SIZE; i++) cout << values[i] << " ";
  64. cout << "\nState: ";
  65. for (int i = 0; i < TABLE_SIZE; i++) cout << state[i] << " ";
  66. cout << endl;
  67.  
  68. cout << "Search 11: " << search(11, keys, values, state) << endl;
  69. cout << "Delete 11: " << (remove(11, keys, values, state) ? "Done" : "Not found") << endl;
  70.  
  71. cout << "Keys: ";
  72. for (int i = 0; i < TABLE_SIZE; i++) cout << keys[i] << " ";
  73. cout << "\nValues: ";
  74. for (int i = 0; i < TABLE_SIZE; i++) cout << values[i] << " ";
  75. cout << "\nState: ";
  76. for (int i = 0; i < TABLE_SIZE; i++) cout << state[i] << " ";
  77. cout << endl;
  78.  
  79. return 0;
  80. }
  81.  
Success #stdin #stdout 0s 5288KB
stdin
Standard input is empty
stdout
Keys:    -1 1 11 21 -1 -1 -1 -1 -1 -1 
Values:  -1 100 200 300 -1 -1 -1 -1 -1 -1 
State:   0 1 1 1 0 0 0 0 0 0 
Search 11: 200
Delete 11: Done
Keys:    -1 1 -1 21 -1 -1 -1 -1 -1 -1 
Values:  -1 100 -1 300 -1 -1 -1 -1 -1 -1 
State:   0 1 2 1 0 0 0 0 0 0