Advertisement
Guest User

Untitled

a guest
Nov 18th, 2019
162
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.32 KB | None | 0 0
  1. #include <iostream>
  2. using namespace std;
  3.  
  4. typedef struct list {
  5. int value;
  6. struct list* next;
  7. } list;
  8.  
  9. typedef struct set {
  10. list** hash_values;
  11. } set;
  12.  
  13. set* create_set(int size) {
  14. auto *s = new set;
  15. s->hash_values = (list **) calloc(size, sizeof(list *));
  16. return s;
  17. }
  18.  
  19. int to_hash(int x) {
  20. return abs(x % 1000001);
  21. }
  22.  
  23. void insert(set* s, int x) {
  24. int h = to_hash(x);
  25. list* element = s->hash_values[h];
  26.  
  27. if (element == nullptr) {
  28. element = new list;
  29. element->value = x;
  30. element->next = nullptr;
  31. s->hash_values[h] = element;
  32. return;
  33. }
  34.  
  35. while (element->next != nullptr) {
  36. if (element->value == x) {
  37. return;
  38. }
  39. element = element->next;
  40. }
  41.  
  42. if (element->value == x) {
  43. return;
  44. }
  45. element->next = new list;
  46. element->next->value = x;
  47. element->next->next = nullptr;
  48. }
  49.  
  50. void del(set* s, int x) {
  51. int h = to_hash(x);
  52. list* element = s->hash_values[h];
  53. list* previous = element;
  54. int i = 0;
  55. while (element != nullptr) {
  56. if (element->value == x && i == 0) {
  57. s->hash_values[h] = element->next;
  58. delete element;
  59. return;
  60. }
  61. else if (element->value == x) {
  62. previous->next = element->next;
  63. delete element;
  64. return;
  65. }
  66. previous = element;
  67. element = element->next;
  68. i = 1;
  69. }
  70. }
  71.  
  72. void exists(set* s, int x) {
  73. int h = to_hash(x);
  74. list* element = s->hash_values[h];
  75. if (element != nullptr) {
  76. do {
  77. if (element->value == x) {
  78. cout<<"true\n";
  79. return;
  80. }
  81. element = element->next;
  82. } while (element != nullptr);
  83. }
  84. cout<<"false\n";
  85. }
  86.  
  87. int main() {
  88. freopen("set.in", "r", stdin);
  89. freopen("set.out", "w", stdout);
  90. string command;
  91. int x;
  92. set* hash = create_set(1000001);
  93. while(cin>>command) {
  94. cin >> x;
  95. if (command == "insert")
  96. {
  97. insert(hash, x);
  98. }
  99. if (command == "exists")
  100. {
  101. exists(hash, x);
  102. }
  103. if (command == "delete")
  104. {
  105. del(hash, x);
  106. }
  107. }
  108. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement