Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <stdlib.h>
- #include <time.h>
- #define N 45
- #define S 30
- #define MAX 100
- using namespace std;
- struct node {
- int key;
- int value;
- struct node* next = NULL;
- };
- int getRandom();
- int hash(int key);
- void push(int key, int value, node* hashTable[]);
- node* find(int key, node* hashTable[]);
- void pop(int key, node* hashTable[]);
- void print(node* hashTable[]);
- int main() {
- srand(time(NULL));
- node* hashTable[S] = { NULL };
- for (int i = 0; i < N; i++) {
- int value = getRandom();
- push(value, value % 2, hashTable);
- }
- cout << "Before removing even elements:" << endl;
- print(hashTable);
- for (int i = 1; i <= MAX; i++) {
- node* p = find(i, hashTable);
- if (p != NULL && p->value == 0) {
- pop(i, hashTable);
- }
- }
- cout << "After removing even elements:" << endl;
- print(hashTable);
- return 0;
- }
- int getRandom() {
- return rand() % MAX + 1;
- }
- int hash_func(int key) {
- return key % S;
- }
- void push(int key, int value, node* hashTable[]) {
- int hashNumber = hash_func(key);
- node* newHashNode = (struct node*)malloc(sizeof(struct node));
- newHashNode->key = key;
- newHashNode->value = value;
- newHashNode->next = NULL;
- node* hashNode = hashTable[hashNumber];
- if (hashNode == NULL) {
- hashTable[hashNumber] = newHashNode;
- return;
- } else {
- while (hashNode->next != NULL) {
- hashNode = hashNode->next;
- }
- hashNode->next = newHashNode;
- }
- }
- node* find(int key, node* hashTable[]) {
- bool flag = false;
- int hashNumber = hash_func(key);
- node* hashNode = hashTable[hashNumber];
- while (hashNode != NULL) {
- if (hashNode->key == key) {
- return hashNode;
- }
- hashNode = hashNode->next;
- }
- return NULL;
- }
- void pop(int key, node* hashTable[]) {
- int hashNumber = hash_func(key);
- node* hashNode = hashTable[hashNumber];
- while (hashNode != NULL) {
- if (hashNode->key == key) {
- if (hashNode->next == NULL) {
- hashTable[hashNumber] = NULL;
- hashNode = NULL;
- } else {
- *hashNode = *hashNode->next;
- }
- continue;
- }
- hashNode = hashNode->next;
- }
- }
- void print(node* hashTable[]) {
- bool flagTable = false;
- cout << endl << "***HASH TABLE***" << endl;
- for (int i = 0; i < S; i++) {
- bool flag = false;
- node* hashNode = hashTable[i];
- cout << "i[" << i << "]: ";
- while (hashNode != NULL) {
- flag = true;
- flagTable = true;
- cout << hashNode->key << " ";
- hashNode = hashNode->next;
- }
- if (flag == false) {
- cout << "NONE";
- }
- cout << endl;
- }
- if (flagTable == false) {
- cout << "-EMPTY-" << endl;
- }
- cout << "*******END*******" << endl << endl;
- }
Add Comment
Please, Sign In to add comment