Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include "time.h"
- #include "string"
- using namespace std;
- int coun;
- class List
- {
- class Node //узел(эл-т)
- {
- public:
- Node* pNext;
- char* data;
- Node(char* data = nullptr, Node* pNext = nullptr)
- {
- this->data = data;
- this->pNext = pNext;
- }
- };
- Node* head;
- int size;
- public:
- List()
- {
- size = 0;
- head = nullptr;
- }
- ~List()
- {
- while (size)
- {
- popfront();
- }
- }
- //проверяем наличие строки(есть такая или нет)
- bool compare(char* key)
- {
- Node* current = head;
- while (current)
- {
- coun++;
- if (strcmp(current->data, key) == 0) // обе строки равны
- {
- return false;
- }
- current = current->pNext;
- }
- return true;
- }
- //удаление первого элемента в списке
- void popfront()
- {
- Node* temp = head;
- head = head->pNext;
- delete temp;
- size--;
- }
- //добавление элемента в конец списка
- void pushback(char* data)
- {
- if (head == nullptr)
- {
- //создаем новый элемент и передаем данные в конструктор
- head = new Node(data);
- }
- else
- {
- Node* current = this->head;
- // идем по элементам, до тех пор пока не найдем элемент с указателем на NULL
- while (current->pNext != nullptr)
- {
- current = current->pNext;
- }
- current->pNext = new Node(data); // создаем новый элемент и присваем адрес
- }
- size++;
- }
- };
- class Table
- {
- List* tab;
- int q;
- // вычисление хеш-функции по схеме Горнера
- int hashFunction(char* key)
- {
- int i = 0;
- for (int j = 0; j < strlen(key); j++)
- {
- i = i * 31 + key[j];
- i = i % q;
- }
- return i;
- }
- public:
- // Конструктор с параметром q(простое число)
- Table(int q)
- {
- this->q = q;
- tab = new List[q];
- }
- // Деструктор
- ~Table()
- {
- delete[] tab;
- }
- // Вставка
- void insert(char* key)
- {
- int c = hashFunction(key);
- if (tab[c].compare(key))
- {
- tab[c].pushback(key);
- }
- }
- };
- int main()
- {
- setlocale(LC_ALL, "rus");
- srand(time(0));
- int N, q, l;
- cout << "Введите значение N" << endl;
- scanf_s("%d", &N);
- cout << "Введите значение q (>=N)" << endl;
- scanf_s("%d", &q);
- cout << "Введите длину строки" << endl;
- scanf_s("%d", &l);
- Table t(q);
- for (int i = 0; i < N - 1; i++)
- {
- char* s = new char[l + 1];
- for (int j = 0; j < l; j++)
- {
- s[j] = (char('a' + rand() % 3));
- }
- s[l] = '\0';
- t.insert(s);
- }
- cout << endl << "Количество сравнений: " << coun << endl;
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement