Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include "stdio.h"
- #include "malloc.h"
- #include "stdlib.h"
- #include "string.h"
- using namespace std;
- struct DLL
- {
- char* profession; //key in hashTable
- float salary;
- DLL* pNext;
- };
- struct HashTable
- {
- DLL** accessTable;
- int size;
- };
- DLL* createElement(char*, float);
- void initHashTable(HashTable*, int);
- void insertHashTable(HashTable, DLL*);
- int fhash(char*, int);
- void printList(int pos, DLL**);
- void main()
- {
- FILE* pFile = fopen("Sursa.txt", "r");
- HashTable hashTable;
- //init hashTable
- initHashTable(&hashTable, 31);
- if (pFile)
- {
- char buffer[100]; float salary;
- fscanf(pFile, "%s", buffer);
- while (!feof(pFile))
- {
- fscanf(pFile, "%f", &salary);
- //1. create an element of type List*
- DLL* newElement = createElement(buffer, salary);
- //2. insert the newly created element
- insertHashTable(hashTable, newElement);
- fscanf(pFile, "%s", buffer);
- }
- fclose(pFile);
- }
- for (int i = 0; i < hashTable.size; i++)
- {
- printList(i, hashTable.accessTable);
- }
- }
- void printList(int pos, DLL** accessTable)
- {
- if (accessTable[pos] == NULL)
- {
- printf("%d: NULL\n",pos);
- }
- else
- {
- DLL* temp = accessTable[pos];
- printf("%d: ", pos);
- while (temp)
- {
- printf("%f; ", temp->salary);
- temp = temp->pNext;
- }
- printf("\n");
- }
- }
- int fhash(char* key, int size)
- {
- int suma = 0;
- for (int i = 0; i < strlen(key); i++)
- suma += key[i];
- return suma % size;
- }
- void insertHashTable(HashTable hashTable, DLL* element)
- {
- int index = fhash(element->profession, hashTable.size);
- if (hashTable.accessTable[index] != NULL)
- {
- DLL* tmp = hashTable.accessTable[index];
- while (tmp->pNext)
- tmp = tmp->pNext;
- tmp->pNext = element;
- }
- else
- {
- hashTable.accessTable[index] = element;
- }
- }
- void initHashTable(HashTable* hashTable, int size)
- {
- hashTable->size = size;
- hashTable->accessTable = (DLL**)malloc(sizeof(DLL*)*size);
- memset(hashTable->accessTable, NULL, sizeof(DLL*)*size);
- }
- DLL* createElement(char* buffer, float salary)
- {
- //1.allocate memory for the new element
- DLL* newElement = (DLL*)malloc(sizeof(DLL));
- //2.initialize it with the params
- //(the connection attributes should remain NULL)
- newElement->pNext = NULL;
- newElement->salary = salary;
- newElement->profession = (char*)malloc(strlen(buffer) + 1);
- strcpy(newElement->profession, buffer);
- //3.return the new element
- return newElement;
- }
Advertisement
Add Comment
Please, Sign In to add comment